repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Symbols/ErrorMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class ErrorMethodSymbol Inherits MethodSymbol Public Shared ReadOnly UnknownMethod As ErrorMethodSymbol = New ErrorMethodSymbol(ErrorTypeSymbol.UnknownResultType, ErrorTypeSymbol.UnknownResultType, String.Empty) Private ReadOnly _containingType As TypeSymbol Private ReadOnly _returnType As TypeSymbol Private ReadOnly _name As String Public Sub New(containingType As TypeSymbol, returnType As TypeSymbol, name As String) _containingType = containingType _returnType = returnType _name = name End Sub Public Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return Microsoft.Cci.CallingConvention.Default End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Return SpecializedCollections.EmptyEnumerable(Of Microsoft.Cci.SecurityAttribute)() End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return _returnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class ErrorMethodSymbol Inherits MethodSymbol Public Shared ReadOnly UnknownMethod As ErrorMethodSymbol = New ErrorMethodSymbol(ErrorTypeSymbol.UnknownResultType, ErrorTypeSymbol.UnknownResultType, String.Empty) Private ReadOnly _containingType As TypeSymbol Private ReadOnly _returnType As TypeSymbol Private ReadOnly _name As String Public Sub New(containingType As TypeSymbol, returnType As TypeSymbol, name As String) _containingType = containingType _returnType = returnType _name = name End Sub Public Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return Microsoft.Cci.CallingConvention.Default End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Public End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Return SpecializedCollections.EmptyEnumerable(Of Microsoft.Cci.SecurityAttribute)() End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return _returnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/CodeGen/Optimizer/StackScheduler.DummyLocal.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler Private Class DummyLocal Inherits SynthesizedLocal Public Sub New(container As Symbol) MyBase.New(container, Nothing, SynthesizedLocalKind.OptimizerTemp) End Sub Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen Partial Friend Class StackScheduler Private Class DummyLocal Inherits SynthesizedLocal Public Sub New(container As Symbol) MyBase.New(container, Nothing, SynthesizedLocalKind.OptimizerTemp) End Sub Friend Overrides Function ComputeType(Optional containingBinder As Binder = Nothing) As TypeSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/OmniSharp/CodeActions/OmniSharpCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CodeActions { internal static class OmniSharpCodeAction { public static ImmutableArray<CodeAction> GetNestedCodeActions(this CodeAction codeAction) => codeAction.NestedCodeActions; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CodeActions { internal static class OmniSharpCodeAction { public static ImmutableArray<CodeAction> GetNestedCodeActions(this CodeAction codeAction) => codeAction.NestedCodeActions; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/NoOpPersistentStorage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal class NoOpPersistentStorage : IChecksummedPersistentStorage { private static readonly IChecksummedPersistentStorage Instance = new NoOpPersistentStorage(); private NoOpPersistentStorage() { } public static IChecksummedPersistentStorage GetOrThrow(OptionSet optionSet) => optionSet.GetOption(StorageOptions.DatabaseMustSucceed) ? throw new InvalidOperationException("Database was not supported") : Instance; public void Dispose() { } public ValueTask DisposeAsync() { return ValueTaskFactory.CompletedTask; } public Task<bool> ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public struct TestAccessor { public static readonly IChecksummedPersistentStorage StorageInstance = Instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PersistentStorage; using Microsoft.CodeAnalysis.Storage; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { internal class NoOpPersistentStorage : IChecksummedPersistentStorage { private static readonly IChecksummedPersistentStorage Instance = new NoOpPersistentStorage(); private NoOpPersistentStorage() { } public static IChecksummedPersistentStorage GetOrThrow(OptionSet optionSet) => optionSet.GetOption(StorageOptions.DatabaseMustSucceed) ? throw new InvalidOperationException("Database was not supported") : Instance; public void Dispose() { } public ValueTask DisposeAsync() { return ValueTaskFactory.CompletedTask; } public Task<bool> ChecksumMatchesAsync(string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> ChecksumMatchesAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(ProjectKey project, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<Stream?> ReadStreamAsync(DocumentKey document, string name, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.Null<Stream>(); public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(ProjectKey projectKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public Task<bool> WriteStreamAsync(DocumentKey documentKey, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken) => SpecializedTasks.False; public struct TestAccessor { public static readonly IChecksummedPersistentStorage StorageInstance = Instance; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Conditional.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects 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 Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Conditional Inherits BasicTestBase #Region "Conditional Attribute Type tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalAttrDefs As String = <![CDATA[ Imports System Imports System.Diagnostics ' Applied conditional attribute <Conditional("cond1")> _ Public Class PreservedAppliedAttribute Inherits Attribute End Class <Conditional("cond2")> _ Public Class OmittedAppliedAttribute Inherits Attribute End Class ' Inherited conditional attribute <Conditional("cond3_dummy")> _ Public Class BasePreservedInheritedAttribute Inherits Attribute End Class <Conditional("cond3")> _ Public Class PreservedInheritedAttribute Inherits BasePreservedInheritedAttribute End Class <Conditional("cond4")> _ Public Class BaseOmittedInheritedAttribute Inherits Attribute End Class <Conditional("cond5")> _ Public Class OmittedInheritedAttribute Inherits BaseOmittedInheritedAttribute End Class ' Multiple conditional attributes <Conditional("cond6"), Conditional("cond7"), Conditional("cond8")> _ Public Class PreservedMultipleAttribute Inherits Attribute End Class <Conditional("cond9")> _ Public Class BaseOmittedMultipleAttribute Inherits Attribute End Class <Conditional("cond10"), Conditional("cond11")> _ Public Class OmittedMultipleAttribute Inherits BaseOmittedMultipleAttribute End Class ' Partially preserved applied conditional attribute ' This attribute has its conditional constant defined midway through the source file. Hence it is conditionally emitted in metadata only for some symbols. <Conditional("condForPartiallyPreservedAppliedAttribute")> _ Public Class PartiallyPreservedAppliedAttribute Inherits Attribute End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalAttributesApplied As String = <![CDATA[ <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustInherit Class Z <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Function m(<PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> param1 As Integer) _ As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer #Const condForPartiallyPreservedAppliedAttribute = True Return 0 End Function <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public f As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Property p1() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Get Return m_p1 End Get #Const condForPartiallyPreservedAppliedAttribute = False <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Set(value As Integer) m_p1 = value End Set End Property Private m_p1 As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride ReadOnly Property p2() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride Property p3() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Event e As Action End Class #Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Enum E <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ A = 1 End Enum <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Structure S End Structure Public Class Test Public Shared Sub Main() End Sub End Class ]]>.Value Private ReadOnly _commonValidatorForCondAttrType As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) ' Each Tuple indicates: <Attributes, hasPartiallyPreservedAppliedAttribute> ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArrayBuilder = ArrayBuilder(Of Tuple(Of ImmutableArray(Of VisualBasicAttributeData), Boolean)).GetInstance() Dim classZ = m.GlobalNamespace.GetTypeMember("Z") attributesArrayBuilder.Add(Tuple.Create(classZ.GetAttributes(), False)) Dim methodM = classZ.GetMember(Of MethodSymbol)("m") attributesArrayBuilder.Add(Tuple.Create(methodM.GetAttributes(), False)) attributesArrayBuilder.Add(Tuple.Create(methodM.GetReturnTypeAttributes(), False)) Dim param1 = methodM.Parameters(0) attributesArrayBuilder.Add(Tuple.Create(param1.GetAttributes(), False)) Dim fieldF = classZ.GetMember(Of FieldSymbol)("f") attributesArrayBuilder.Add(Tuple.Create(fieldF.GetAttributes(), True)) Dim propP1 = classZ.GetMember(Of PropertySymbol)("p1") attributesArrayBuilder.Add(Tuple.Create(propP1.GetAttributes(), True)) Dim propGetMethod = propP1.GetMethod attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetAttributes(), True)) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), True)) Dim propSetMethod = propP1.SetMethod attributesArrayBuilder.Add(Tuple.Create(propSetMethod.GetAttributes(), False)) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim propP2 = classZ.GetMember(Of PropertySymbol)("p2") attributesArrayBuilder.Add(Tuple.Create(propP2.GetAttributes(), False)) propGetMethod = propP2.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) Dim propP3 = classZ.GetMember(Of PropertySymbol)("p3") attributesArrayBuilder.Add(Tuple.Create(propP3.GetAttributes(), False)) propGetMethod = propP3.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) propSetMethod = propP3.SetMethod Assert.Equal(0, propSetMethod.GetAttributes().Length) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim eventE = classZ.GetMember(Of EventSymbol)("e") attributesArrayBuilder.Add(Tuple.Create(eventE.GetAttributes(), False)) If isFromSource Then Assert.Equal(0, eventE.AssociatedField.GetAttributes().Length) Assert.Equal(0, eventE.AddMethod.GetAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.AddMethod.GetAttributes())) AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.RemoveMethod.GetAttributes())) End If Assert.Equal(0, eventE.AddMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetReturnTypeAttributes().Length) Dim enumE = m.GlobalNamespace.GetTypeMember("E") attributesArrayBuilder.Add(Tuple.Create(enumE.GetAttributes(), True)) Dim fieldA = enumE.GetMember(Of FieldSymbol)("A") attributesArrayBuilder.Add(Tuple.Create(fieldA.GetAttributes(), True)) Dim structS = m.GlobalNamespace.GetTypeMember("S") attributesArrayBuilder.Add(Tuple.Create(structS.GetAttributes(), True)) For Each tup In attributesArrayBuilder ' PreservedAppliedAttribute and OmittedAppliedAttribute have applied conditional attributes, such that ' (a) PreservedAppliedAttribute is conditionally applied to symbols ' (b) OmittedAppliedAttribute is conditionally NOT applied to symbols ' PreservedInheritedAttribute and OmittedInheritedAttribute have inherited conditional attributes, such that ' (a) PreservedInheritedAttribute is conditionally applied to symbols ' (b) OmittedInheritedAttribute is conditionally NOT applied to symbols ' PreservedMultipleAttribute and OmittedMultipleAttribute have multiple applied/inherited conditional attributes, such that ' (a) PreservedMultipleAttribute is conditionally applied to symbols ' (b) OmittedMultipleAttribute is conditionally NOT applied to symbols ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArray As ImmutableArray(Of VisualBasicAttributeData) = tup.Item1 Dim actualAttributeNames = GetAttributeNames(attributesArray) If isFromSource Then ' All attributes should be present for source symbols AssertEx.SetEqual({"PreservedAppliedAttribute", "OmittedAppliedAttribute", "PreservedInheritedAttribute", "OmittedInheritedAttribute", "PreservedMultipleAttribute", "OmittedMultipleAttribute", "PartiallyPreservedAppliedAttribute"}, actualAttributeNames) Else Dim hasPartiallyPreservedAppliedAttribute = tup.Item2 Dim expectedAttributeNames As String() If Not hasPartiallyPreservedAppliedAttribute Then ' Only PreservedAppliedAttribute, PreservedInheritedAttribute, PreservedMultipleAttribute should be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute"} Else ' PartiallyPreservedAppliedAttribute must also be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute", "PartiallyPreservedAppliedAttribute"} End If AssertEx.SetEqual(expectedAttributeNames, actualAttributeNames) End If Next attributesArrayBuilder.Free() End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalAttrDefs & s_commonTestSource_ConditionalAttributesApplied Dim compilation = CreateCompilationWithMscorlib40({Parse(testSource, parseOpts)}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String) TestConditionAttributeType_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionAttributeType_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalAttrDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalAttributesApplied Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") ' Different source files, different compilation Dim comp1 = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1)}, options:=TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create("comp2", {Parse(source2, parseOpts2)}, {MscorlibRef, New VisualBasicCompilationReference(comp1)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp2, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionAttributeType_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond6 = True ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond6", True)) TestConditionAttributeType_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionAttributeType_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionAttributeType_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4 = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = Nothing ' The last definition holds for CC constants. #Const cond6 = True #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = Nothing ' Source definition for CC constants overrides command line /define definitions. #Const cond6 = True ' Mix match source and command line defines. #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs, preprocessorSymbols:=preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 1)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <Fact> Public Sub TestNestedTypeMember() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Conditional(Outer.Nested.ConstStr)> _ <Outer> _ Class Outer Inherits Attribute Public Class Nested Public Const ConstStr As String = "str" End Class End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub #End Region #End Region #Region "Conditional Method tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalMethodDefs As String = <![CDATA[ Imports System Imports System.Diagnostics Public Class BaseZ <Conditional("cond3_base")> _ Public Overridable Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.PreservedCalls_InheritedConditional_Method") End Sub <Conditional("cond4_base")> _ Public Overridable Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.OmittedCalls_InheritedConditional_Method") End Sub End Class Public Interface I ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("dummy")> Sub PartiallyPreservedCalls_Interface_Method() End Interface Public Class Z Inherits BaseZ Implements I <Conditional("cond1")> _ Public Sub PreservedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_AppliedConditional_Method") End Sub <Conditional("cond2")> _ Public Sub OmittedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AppliedConditional_Method") End Sub ' Conditional symbols are not inherited by overriding methods in VB <Conditional("cond3")> _ Public Overrides Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_InheritedConditional_Method") End Sub #Const cond4_base = "Conditional symbols are not inherited by overriding methods in VB" <Conditional("cond4")> _ Public Overrides Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_InheritedConditional_Method") End Sub <Conditional("cond5"), Conditional("cond6")> _ Public Sub PreservedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.PreservedCalls_MultipleConditional_Method") End Sub <Conditional("cond7"), Conditional("cond8")> _ Public Sub OmittedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.OmittedCalls_MultipleConditional_Method") End Sub ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("cond9")> Public Sub PartiallyPreservedCalls_Interface_Method() Implements I.PartiallyPreservedCalls_Interface_Method System.Console.WriteLine("Z.PartiallyPreservedCalls_Interface_Method") End Sub ' Conditional attributes are ignored for functions <Conditional("cond10")> Public Function PreservedCalls_Function() As Integer System.Console.WriteLine("Z.PreservedCalls_Function") Return 0 End Function <Conditional(""), Conditional(Nothing)> _ Public Sub OmittedCalls_AlwaysFalseConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AlwaysFalseConditional_Method") End Sub <Conditional("condForPartiallyPreservedAppliedAttribute")> Public Sub PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(i As Integer) System.Console.WriteLine("Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method" & i) End Sub End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalMethodCalls As String = <![CDATA[ Module Module1 Public Sub Main() Dim z = New Z() z.PreservedCalls_AppliedConditional_Method() z.OmittedCalls_AppliedConditional_Method() z.PreservedCalls_InheritedConditional_Method() z.OmittedCalls_InheritedConditional_Method() z.PreservedCalls_MultipleConditional_Method() z.OmittedCalls_MultipleConditional_Method() z.OmittedCalls_AlwaysFalseConditional_Method() z.PartiallyPreservedCalls_Interface_Method() ' Omitted DirectCast(z, I).PartiallyPreservedCalls_Interface_Method() ' Preserved Console.WriteLine(z.PreservedCalls_Function()) ' Second and fourth calls are preserved, first, third and fifth calls are omitted. z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(1) # Const condForPartiallyPreservedAppliedAttribute = True z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(2) # Const condForPartiallyPreservedAppliedAttribute = 0 z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(3) # Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(4) # Const condForPartiallyPreservedAppliedAttribute = Nothing z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(5) End Sub End Module ]]>.Value Private Shared ReadOnly s_commonExpectedOutput_ConditionalMethodsTest As String = "Z.PreservedCalls_AppliedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_InheritedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_MultipleConditional_Method" & Environment.NewLine & "Z.PartiallyPreservedCalls_Interface_Method" & Environment.NewLine & "Z.PreservedCalls_Function" & Environment.NewLine & "0" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method2" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method4" & Environment.NewLine Private Sub TestConditionalMethod_SameSource(condDefs As String) TestConditionalMethod_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalMethodDefs & s_commonTestSource_ConditionalMethodCalls Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(testSource, parseOpts)}, {MscorlibRef, SystemCoreRef, MsvbRef}) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionalMethod_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalMethodDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalMethodCalls Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) ' Different source files, different compilation Dim comp1 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef, comp1.ToMetadataReference()}, TestOptions.ReleaseExe) CompileAndVerify(comp2, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionalMethod_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond5 = True ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond5", True)) TestConditionalMethod_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionalMethod_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionalMethod_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4_base = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4_base", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs, preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 0), New KeyValuePair(Of String, Object)("cond5", True)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest_02() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub #Const VAR4 = False Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546094")> <Fact> Public Sub ConditionalAttributeOnPropertySetter() Dim source = <compilation> <file name="a.vb"> Imports System Class TestClass WriteOnly Property goo() As String &lt;Diagnostics.Conditional("N")&gt; Set(ByVal Value As String) Console.WriteLine("Property Called") End Set End Property End Class Module M1 Sub Main() Dim t As New TestClass() t.goo = "abds" End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Property Called]]>) End Sub #End Region <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttributeInNetModule() Const source = " Imports System.Diagnostics Class C Sub M() N1() N2() End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim comp = CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(source, parseOptions)}, options:=TestOptions.ReleaseModule) CompileAndVerify(comp, verify:=Verification.Fails).VerifyIL("C.M", " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""Sub C.N1()"" IL_0006: ret } ") End Sub #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.IO Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects 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 Roslyn.Test.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Conditional Inherits BasicTestBase #Region "Conditional Attribute Type tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalAttrDefs As String = <![CDATA[ Imports System Imports System.Diagnostics ' Applied conditional attribute <Conditional("cond1")> _ Public Class PreservedAppliedAttribute Inherits Attribute End Class <Conditional("cond2")> _ Public Class OmittedAppliedAttribute Inherits Attribute End Class ' Inherited conditional attribute <Conditional("cond3_dummy")> _ Public Class BasePreservedInheritedAttribute Inherits Attribute End Class <Conditional("cond3")> _ Public Class PreservedInheritedAttribute Inherits BasePreservedInheritedAttribute End Class <Conditional("cond4")> _ Public Class BaseOmittedInheritedAttribute Inherits Attribute End Class <Conditional("cond5")> _ Public Class OmittedInheritedAttribute Inherits BaseOmittedInheritedAttribute End Class ' Multiple conditional attributes <Conditional("cond6"), Conditional("cond7"), Conditional("cond8")> _ Public Class PreservedMultipleAttribute Inherits Attribute End Class <Conditional("cond9")> _ Public Class BaseOmittedMultipleAttribute Inherits Attribute End Class <Conditional("cond10"), Conditional("cond11")> _ Public Class OmittedMultipleAttribute Inherits BaseOmittedMultipleAttribute End Class ' Partially preserved applied conditional attribute ' This attribute has its conditional constant defined midway through the source file. Hence it is conditionally emitted in metadata only for some symbols. <Conditional("condForPartiallyPreservedAppliedAttribute")> _ Public Class PartiallyPreservedAppliedAttribute Inherits Attribute End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalAttributesApplied As String = <![CDATA[ <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustInherit Class Z <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Function m(<PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> param1 As Integer) _ As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer #Const condForPartiallyPreservedAppliedAttribute = True Return 0 End Function <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public f As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Property p1() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Get Return m_p1 End Get #Const condForPartiallyPreservedAppliedAttribute = False <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Set(value As Integer) m_p1 = value End Set End Property Private m_p1 As Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride ReadOnly Property p2() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public MustOverride Property p3() As <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> Integer <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Event e As Action End Class #Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Enum E <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ A = 1 End Enum <PreservedAppliedAttribute, OmittedAppliedAttribute, PreservedInheritedAttribute, OmittedInheritedAttribute, PreservedMultipleAttribute, OmittedMultipleAttribute, PartiallyPreservedAppliedAttribute> _ Public Structure S End Structure Public Class Test Public Shared Sub Main() End Sub End Class ]]>.Value Private ReadOnly _commonValidatorForCondAttrType As Func(Of Boolean, Action(Of ModuleSymbol)) = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) ' Each Tuple indicates: <Attributes, hasPartiallyPreservedAppliedAttribute> ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArrayBuilder = ArrayBuilder(Of Tuple(Of ImmutableArray(Of VisualBasicAttributeData), Boolean)).GetInstance() Dim classZ = m.GlobalNamespace.GetTypeMember("Z") attributesArrayBuilder.Add(Tuple.Create(classZ.GetAttributes(), False)) Dim methodM = classZ.GetMember(Of MethodSymbol)("m") attributesArrayBuilder.Add(Tuple.Create(methodM.GetAttributes(), False)) attributesArrayBuilder.Add(Tuple.Create(methodM.GetReturnTypeAttributes(), False)) Dim param1 = methodM.Parameters(0) attributesArrayBuilder.Add(Tuple.Create(param1.GetAttributes(), False)) Dim fieldF = classZ.GetMember(Of FieldSymbol)("f") attributesArrayBuilder.Add(Tuple.Create(fieldF.GetAttributes(), True)) Dim propP1 = classZ.GetMember(Of PropertySymbol)("p1") attributesArrayBuilder.Add(Tuple.Create(propP1.GetAttributes(), True)) Dim propGetMethod = propP1.GetMethod attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetAttributes(), True)) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), True)) Dim propSetMethod = propP1.SetMethod attributesArrayBuilder.Add(Tuple.Create(propSetMethod.GetAttributes(), False)) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim propP2 = classZ.GetMember(Of PropertySymbol)("p2") attributesArrayBuilder.Add(Tuple.Create(propP2.GetAttributes(), False)) propGetMethod = propP2.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) Dim propP3 = classZ.GetMember(Of PropertySymbol)("p3") attributesArrayBuilder.Add(Tuple.Create(propP3.GetAttributes(), False)) propGetMethod = propP3.GetMethod Assert.Equal(0, propGetMethod.GetAttributes().Length) attributesArrayBuilder.Add(Tuple.Create(propGetMethod.GetReturnTypeAttributes(), False)) propSetMethod = propP3.SetMethod Assert.Equal(0, propSetMethod.GetAttributes().Length) Assert.Equal(0, propSetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, propSetMethod.Parameters(0).GetAttributes().Length) Dim eventE = classZ.GetMember(Of EventSymbol)("e") attributesArrayBuilder.Add(Tuple.Create(eventE.GetAttributes(), False)) If isFromSource Then Assert.Equal(0, eventE.AssociatedField.GetAttributes().Length) Assert.Equal(0, eventE.AddMethod.GetAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.AddMethod.GetAttributes())) AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(eventE.RemoveMethod.GetAttributes())) End If Assert.Equal(0, eventE.AddMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, eventE.RemoveMethod.GetReturnTypeAttributes().Length) Dim enumE = m.GlobalNamespace.GetTypeMember("E") attributesArrayBuilder.Add(Tuple.Create(enumE.GetAttributes(), True)) Dim fieldA = enumE.GetMember(Of FieldSymbol)("A") attributesArrayBuilder.Add(Tuple.Create(fieldA.GetAttributes(), True)) Dim structS = m.GlobalNamespace.GetTypeMember("S") attributesArrayBuilder.Add(Tuple.Create(structS.GetAttributes(), True)) For Each tup In attributesArrayBuilder ' PreservedAppliedAttribute and OmittedAppliedAttribute have applied conditional attributes, such that ' (a) PreservedAppliedAttribute is conditionally applied to symbols ' (b) OmittedAppliedAttribute is conditionally NOT applied to symbols ' PreservedInheritedAttribute and OmittedInheritedAttribute have inherited conditional attributes, such that ' (a) PreservedInheritedAttribute is conditionally applied to symbols ' (b) OmittedInheritedAttribute is conditionally NOT applied to symbols ' PreservedMultipleAttribute and OmittedMultipleAttribute have multiple applied/inherited conditional attributes, such that ' (a) PreservedMultipleAttribute is conditionally applied to symbols ' (b) OmittedMultipleAttribute is conditionally NOT applied to symbols ' PartiallyPreservedAppliedAttribute has its conditional constant defined midway through the source file. ' Hence this attribute is emitted in metadata only for some symbols. Dim attributesArray As ImmutableArray(Of VisualBasicAttributeData) = tup.Item1 Dim actualAttributeNames = GetAttributeNames(attributesArray) If isFromSource Then ' All attributes should be present for source symbols AssertEx.SetEqual({"PreservedAppliedAttribute", "OmittedAppliedAttribute", "PreservedInheritedAttribute", "OmittedInheritedAttribute", "PreservedMultipleAttribute", "OmittedMultipleAttribute", "PartiallyPreservedAppliedAttribute"}, actualAttributeNames) Else Dim hasPartiallyPreservedAppliedAttribute = tup.Item2 Dim expectedAttributeNames As String() If Not hasPartiallyPreservedAppliedAttribute Then ' Only PreservedAppliedAttribute, PreservedInheritedAttribute, PreservedMultipleAttribute should be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute"} Else ' PartiallyPreservedAppliedAttribute must also be emitted in metadata expectedAttributeNames = {"PreservedAppliedAttribute", "PreservedInheritedAttribute", "PreservedMultipleAttribute", "PartiallyPreservedAppliedAttribute"} End If AssertEx.SetEqual(expectedAttributeNames, actualAttributeNames) End If Next attributesArrayBuilder.Free() End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalAttrDefs & s_commonTestSource_ConditionalAttributesApplied Dim compilation = CreateCompilationWithMscorlib40({Parse(testSource, parseOpts)}, options:=TestOptions.ReleaseExe) CompileAndVerify(compilation, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub Private Sub TestConditionAttributeType_SameSource(condDefs As String) TestConditionAttributeType_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionAttributeType_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionAttributeType_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalAttrDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalAttributesApplied Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") ' Different source files, different compilation Dim comp1 = CreateCompilationWithMscorlib40({Parse(source1, parseOpts1)}, options:=TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create("comp2", {Parse(source2, parseOpts2)}, {MscorlibRef, New VisualBasicCompilationReference(comp1)}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp2, sourceSymbolValidator:=_commonValidatorForCondAttrType(True), symbolValidator:=_commonValidatorForCondAttrType(False), expectedOutput:="") End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionAttributeType_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond6 = True ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond6", True)) TestConditionAttributeType_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionAttributeType_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionAttributeType_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4 = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = Nothing ' The last definition holds for CC constants. #Const cond6 = True #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionAttributeType_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = Nothing ' Source definition for CC constants overrides command line /define definitions. #Const cond6 = True ' Mix match source and command line defines. #Const cond7 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond8 = 2 ' Multiple conditional symbols defined. ]]>.Value TestConditionAttributeType_SameSource(conditionalDefs, preprocessorSymbols:=preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 1)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionAttributeType_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <Fact> Public Sub TestNestedTypeMember() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Diagnostics <Conditional(Outer.Nested.ConstStr)> _ <Outer> _ Class Outer Inherits Attribute Public Class Nested Public Const ConstStr As String = "str" End Class End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub #End Region #End Region #Region "Conditional Method tests" #Region "Common Helpers" Private Shared ReadOnly s_commonTestSource_ConditionalMethodDefs As String = <![CDATA[ Imports System Imports System.Diagnostics Public Class BaseZ <Conditional("cond3_base")> _ Public Overridable Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.PreservedCalls_InheritedConditional_Method") End Sub <Conditional("cond4_base")> _ Public Overridable Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("BaseZ.OmittedCalls_InheritedConditional_Method") End Sub End Class Public Interface I ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("dummy")> Sub PartiallyPreservedCalls_Interface_Method() End Interface Public Class Z Inherits BaseZ Implements I <Conditional("cond1")> _ Public Sub PreservedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_AppliedConditional_Method") End Sub <Conditional("cond2")> _ Public Sub OmittedCalls_AppliedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AppliedConditional_Method") End Sub ' Conditional symbols are not inherited by overriding methods in VB <Conditional("cond3")> _ Public Overrides Sub PreservedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.PreservedCalls_InheritedConditional_Method") End Sub #Const cond4_base = "Conditional symbols are not inherited by overriding methods in VB" <Conditional("cond4")> _ Public Overrides Sub OmittedCalls_InheritedConditional_Method() System.Console.WriteLine("Z.OmittedCalls_InheritedConditional_Method") End Sub <Conditional("cond5"), Conditional("cond6")> _ Public Sub PreservedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.PreservedCalls_MultipleConditional_Method") End Sub <Conditional("cond7"), Conditional("cond8")> _ Public Sub OmittedCalls_MultipleConditional_Method() System.Console.WriteLine("Z.OmittedCalls_MultipleConditional_Method") End Sub ' Conditional attributes are ignored for interface methods, but respected for implementing methods. <Conditional("cond9")> Public Sub PartiallyPreservedCalls_Interface_Method() Implements I.PartiallyPreservedCalls_Interface_Method System.Console.WriteLine("Z.PartiallyPreservedCalls_Interface_Method") End Sub ' Conditional attributes are ignored for functions <Conditional("cond10")> Public Function PreservedCalls_Function() As Integer System.Console.WriteLine("Z.PreservedCalls_Function") Return 0 End Function <Conditional(""), Conditional(Nothing)> _ Public Sub OmittedCalls_AlwaysFalseConditional_Method() System.Console.WriteLine("Z.OmittedCalls_AlwaysFalseConditional_Method") End Sub <Conditional("condForPartiallyPreservedAppliedAttribute")> Public Sub PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(i As Integer) System.Console.WriteLine("Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method" & i) End Sub End Class ]]>.Value Private Shared ReadOnly s_commonTestSource_ConditionalMethodCalls As String = <![CDATA[ Module Module1 Public Sub Main() Dim z = New Z() z.PreservedCalls_AppliedConditional_Method() z.OmittedCalls_AppliedConditional_Method() z.PreservedCalls_InheritedConditional_Method() z.OmittedCalls_InheritedConditional_Method() z.PreservedCalls_MultipleConditional_Method() z.OmittedCalls_MultipleConditional_Method() z.OmittedCalls_AlwaysFalseConditional_Method() z.PartiallyPreservedCalls_Interface_Method() ' Omitted DirectCast(z, I).PartiallyPreservedCalls_Interface_Method() ' Preserved Console.WriteLine(z.PreservedCalls_Function()) ' Second and fourth calls are preserved, first, third and fifth calls are omitted. z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(1) # Const condForPartiallyPreservedAppliedAttribute = True z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(2) # Const condForPartiallyPreservedAppliedAttribute = 0 z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(3) # Const condForPartiallyPreservedAppliedAttribute = "TrueAgain" z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(4) # Const condForPartiallyPreservedAppliedAttribute = Nothing z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method(5) End Sub End Module ]]>.Value Private Shared ReadOnly s_commonExpectedOutput_ConditionalMethodsTest As String = "Z.PreservedCalls_AppliedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_InheritedConditional_Method" & Environment.NewLine & "Z.PreservedCalls_MultipleConditional_Method" & Environment.NewLine & "Z.PartiallyPreservedCalls_Interface_Method" & Environment.NewLine & "Z.PreservedCalls_Function" & Environment.NewLine & "0" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method2" & Environment.NewLine & "Z.PartiallyPreservedCalls_PartiallyPreservedAppliedAttribute_Method4" & Environment.NewLine Private Sub TestConditionalMethod_SameSource(condDefs As String) TestConditionalMethod_SameSource(condDefs, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_SameSource(condDefs As String, preprocessorSymbols As ImmutableArray(Of KeyValuePair(Of String, Object))) ' Same source file Debug.Assert(Not preprocessorSymbols.IsDefault) Dim parseOpts = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbols) Dim testSource As String = condDefs & s_commonTestSource_ConditionalMethodDefs & s_commonTestSource_ConditionalMethodCalls Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(testSource, parseOpts)}, {MscorlibRef, SystemCoreRef, MsvbRef}) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, condDefsSrcFile2 As String) TestConditionalMethod_DifferentSource(condDefsSrcFile1, ImmutableArray.Create(Of KeyValuePair(Of String, Object))(), condDefsSrcFile2, ImmutableArray.Create(Of KeyValuePair(Of String, Object))()) End Sub Private Sub TestConditionalMethod_DifferentSource(condDefsSrcFile1 As String, preprocessorSymbolsSrcFile1 As ImmutableArray(Of KeyValuePair(Of String, Object)), condDefsSrcFile2 As String, preprocessorSymbolsSrcFile2 As ImmutableArray(Of KeyValuePair(Of String, Object))) Dim source1 As String = condDefsSrcFile1 & s_commonTestSource_ConditionalMethodDefs Dim source2 As String = condDefsSrcFile2 & <![CDATA[ Imports System Imports System.Diagnostics ]]>.Value & s_commonTestSource_ConditionalMethodCalls Debug.Assert(Not preprocessorSymbolsSrcFile1.IsDefault) Dim parseOpts1 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile1) Debug.Assert(Not preprocessorSymbolsSrcFile2.IsDefault) Dim parseOpts2 = VisualBasicParseOptions.Default.WithPreprocessorSymbols(preprocessorSymbolsSrcFile2) ' Different source files, same compilation Dim comp = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1), Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) ' Different source files, different compilation Dim comp1 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source1, parseOpts1)}, {MscorlibRef, MsvbRef}, TestOptions.ReleaseDll) Dim comp2 = VisualBasicCompilation.Create(GetUniqueName(), {Parse(source2, parseOpts2)}, {MscorlibRef, MsvbRef, comp1.ToMetadataReference()}, TestOptions.ReleaseExe) CompileAndVerify(comp2, expectedOutput:=s_commonExpectedOutput_ConditionalMethodsTest) End Sub #End Region #Region "Tests" <Fact> Public Sub TestConditionalMethod_01_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond3 = "" #Const cond5 = True ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond5 = "" #Const cond7 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_01_CommandLineDefines() Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond5", True)) TestConditionalMethod_SameSource(condDefs:="", preprocessorSymbols:=preprocessorSymbols) Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond5", ""), New KeyValuePair(Of String, Object)("cond7", True)) TestConditionalMethod_DifferentSource(condDefsSrcFile1:="", preprocessorSymbolsSrcFile1:=preprocessorSymbolsDummy, condDefsSrcFile2:="", preprocessorSymbolsSrcFile2:=preprocessorSymbols) End Sub <Fact> Public Sub TestConditionalMethod_02_SourceDefines() Dim conditionalDefs As String = <![CDATA[ #Const cond1 = 1 #Const cond2 = 1.0 ' Decimal type value is not considered for CC constants. #Const cond3 = "" #Const cond4_base = True ' Conditional attributes are not inherited from base type. #Const cond5 = 1 #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond2 = 1 #Const cond3_dummy = 0 #Const cond5 = "" #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, conditionalDefs) End Sub <Fact> Public Sub TestConditionalMethod_02_CommandLineDefines() ' Mix and match source and command line defines. Dim preprocessorSymbols = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond1", 1), New KeyValuePair(Of String, Object)("cond2", 1.0), New KeyValuePair(Of String, Object)("cond3", ""), New KeyValuePair(Of String, Object)("cond4_base", True), New KeyValuePair(Of String, Object)("cond5", 1)) Dim conditionalDefs As String = <![CDATA[ #Const cond5 = 0 ' One of the conditional symbol is zero, but other conditional symbols for the attribute type are defined. #Const cond6 = True #Const cond7 = 0 #Const cond3 = True ' The last definition holds for CC constants. ]]>.Value TestConditionalMethod_SameSource(conditionalDefs, preprocessorSymbols) ' Mix and match source and command line defines. Dim preprocessorSymbolsDummy = ImmutableArray.Create(Of KeyValuePair(Of String, Object))(New KeyValuePair(Of String, Object)("cond2", 1), New KeyValuePair(Of String, Object)("cond3_dummy", 0), New KeyValuePair(Of String, Object)("cond5", True)) Dim conditionalDefsDummy As String = <![CDATA[ #Const cond7 = True #Const cond8 = True #Const cond9 = True #Const cond10 = True #Const cond11 = True ]]>.Value TestConditionalMethod_DifferentSource(conditionalDefsDummy, preprocessorSymbolsDummy, conditionalDefs, preprocessorSymbols) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546089, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546089")> <Fact> Public Sub CaseInsensitivityTest_02() Dim source = <compilation> <file name="a.vb"> Imports System Module Test &lt;System.Diagnostics.Conditional("VAR4")&gt; Sub Sub1() Console.WriteLine("Sub1 Called") End Sub #Const VAR4 = False Sub Main() #Const var4 = True Sub1() End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Sub1 Called]]>) End Sub <WorkItem(546094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546094")> <Fact> Public Sub ConditionalAttributeOnPropertySetter() Dim source = <compilation> <file name="a.vb"> Imports System Class TestClass WriteOnly Property goo() As String &lt;Diagnostics.Conditional("N")&gt; Set(ByVal Value As String) Console.WriteLine("Property Called") End Set End Property End Class Module M1 Sub Main() Dim t As New TestClass() t.goo = "abds" End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[Property Called]]>) End Sub #End Region <WorkItem(1003274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003274")> <Fact> Public Sub ConditionalAttributeInNetModule() Const source = " Imports System.Diagnostics Class C Sub M() N1() N2() End Sub <Conditional(""Defined"")> Sub N1() End Sub <Conditional(""Undefined"")> Sub N2() End Sub End Class " Dim parseOptions As New VisualBasicParseOptions(preprocessorSymbols:={New KeyValuePair(Of String, Object)("Defined", True)}) Dim comp = CreateCompilationWithMscorlib40({VisualBasicSyntaxTree.ParseText(source, parseOptions)}, options:=TestOptions.ReleaseModule) CompileAndVerify(comp, verify:=Verification.Fails).VerifyIL("C.M", " { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""Sub C.N1()"" IL_0006: ret } ") End Sub #End Region End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Syntax/ISyntaxNodeKindProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; namespace Microsoft.CodeAnalysis.Test.Utilities { public interface ISyntaxNodeKindProvider { string Kind(object node); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Test.Utilities { public interface ISyntaxNodeKindProvider { string Kind(object node); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/CommandLine/CommandLineSourceFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a source file specification stored on command line arguments. /// </summary> [DebuggerDisplay("{Path,nq}")] public struct CommandLineSourceFile { public CommandLineSourceFile(string path, bool isScript) : this(path, isScript, false) { } public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected) { Debug.Assert(!string.IsNullOrEmpty(path)); Path = path; IsScript = isScript; IsInputRedirected = isInputRedirected; } /// <summary> /// Resolved absolute path of the source file (does not contain wildcards). /// </summary> /// <remarks> /// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle. /// </remarks> public string Path { get; } /// <summary> /// True if the input has been redirected from the standard input stream. /// </summary> public bool IsInputRedirected { get; } /// <summary> /// True if the file should be treated as a script file. /// </summary> public bool IsScript { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a source file specification stored on command line arguments. /// </summary> [DebuggerDisplay("{Path,nq}")] public struct CommandLineSourceFile { public CommandLineSourceFile(string path, bool isScript) : this(path, isScript, false) { } public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected) { Debug.Assert(!string.IsNullOrEmpty(path)); Path = path; IsScript = isScript; IsInputRedirected = isInputRedirected; } /// <summary> /// Resolved absolute path of the source file (does not contain wildcards). /// </summary> /// <remarks> /// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle. /// </remarks> public string Path { get; } /// <summary> /// True if the input has been redirected from the standard input stream. /// </summary> public bool IsInputRedirected { get; } /// <summary> /// True if the file should be treated as a script file. /// </summary> public bool IsScript { get; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Semantic/Binding/LookupTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class LookupTests Inherits BasicTestBase Private Function GetContext(compilation As VisualBasicCompilation, treeName As String, textToFind As String) As Binder Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName) Dim position = CompilationUtils.FindPositionFromText(tree, textToFind) Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel).GetEnclosingBinder(position) End Function <Fact()> Public Sub TestLookupResult() Dim sym1 = New MockAssemblySymbol("hello") ' just a symbol to put in results Dim sym2 = New MockAssemblySymbol("goodbye") ' just a symbol to put in results Dim sym3 = New MockAssemblySymbol("world") ' just a symbol to put in results Dim sym4 = New MockAssemblySymbol("banana") ' just a symbol to put in results Dim sym5 = New MockAssemblySymbol("apple") ' just a symbol to put in results Dim meth1 = New MockMethodSymbol("goo") ' just a symbol to put in results Dim meth2 = New MockMethodSymbol("bag") ' just a symbol to put in results Dim meth3 = New MockMethodSymbol("baz") ' just a symbol to put in results Dim r1 = New LookupResult() r1.SetFrom(SingleLookupResult.Empty) Assert.False(r1.HasSymbol) Assert.False(r1.IsGood) Assert.False(r1.HasDiagnostic) Assert.False(r1.StopFurtherLookup) Dim r2 = SingleLookupResult.Good(sym1) Dim _r2 = New LookupResult() _r2.SetFrom(r2) Assert.True(_r2.HasSymbol) Assert.True(_r2.IsGood) Assert.Same(sym1, _r2.SingleSymbol) Assert.False(_r2.HasDiagnostic) Assert.True(_r2.StopFurtherLookup) Dim r3 = New LookupResult() r3.SetFrom(SingleLookupResult.Ambiguous(ImmutableArray.Create(Of Symbol)(sym1, sym2, sym3), AddressOf GenerateAmbiguity)) Assert.True(r3.HasSymbol) Assert.False(r3.IsGood) Assert.Same(sym1, r3.SingleSymbol) Assert.True(r3.HasDiagnostic) Assert.True(r3.StopFurtherLookup) Dim diag3 = DirectCast(r3.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag3.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag3.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag3.AmbiguousSymbols.Item(2)) Dim r4 = New LookupResult() r4.SetFrom(SingleLookupResult.Inaccessible(sym2, New BadSymbolDiagnostic(sym2, ERRID.ERR_InaccessibleSymbol2, sym2))) Assert.True(r4.HasSymbol) Assert.False(r4.IsGood) Assert.Same(sym2, r4.SingleSymbol) Assert.True(r4.HasDiagnostic) Assert.False(r4.StopFurtherLookup) Dim diag4 = DirectCast(r4.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag4.Code) Assert.Same(sym2, diag4.BadSymbol) Dim r5 = New LookupResult() r5.SetFrom(SingleLookupResult.WrongArity(sym3, ERRID.ERR_IndexedNotArrayOrProc)) Assert.True(r5.HasSymbol) Assert.False(r5.IsGood) Assert.Same(sym3, r5.SingleSymbol) Assert.True(r5.HasDiagnostic) Assert.False(r5.StopFurtherLookup) Dim diag5 = r5.Diagnostic Assert.Equal(ERRID.ERR_IndexedNotArrayOrProc, diag5.Code) Dim r6 = New LookupResult() r6.MergePrioritized(r1) r6.MergePrioritized(r2) Assert.True(r6.HasSymbol) Assert.Same(sym1, r6.SingleSymbol) Assert.False(r6.HasDiagnostic) Assert.True(r6.StopFurtherLookup) r6.Free() Dim r7 = New LookupResult() r7.MergePrioritized(r2) r7.MergePrioritized(r1) Assert.True(r7.HasSymbol) Assert.Same(sym1, r7.SingleSymbol) Assert.False(r7.HasDiagnostic) Assert.True(r7.StopFurtherLookup) Dim r8 = New LookupResult() r8.SetFrom(SingleLookupResult.Good(sym4)) Dim r9 = New LookupResult() r9.SetFrom(r2) r9.MergePrioritized(r8) Assert.True(r9.HasSymbol) Assert.Same(sym1, r9.SingleSymbol) Assert.False(r9.HasDiagnostic) Assert.True(r9.StopFurtherLookup) Dim r10 = New LookupResult() r10.SetFrom(r3) r10.MergePrioritized(r8) r10.MergePrioritized(r2) Assert.True(r10.HasSymbol) Assert.Same(sym1, r10.SingleSymbol) Assert.True(r10.HasDiagnostic) Assert.True(r10.StopFurtherLookup) Dim diag10 = DirectCast(r10.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag10.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag10.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag10.AmbiguousSymbols.Item(2)) Dim r11 = New LookupResult() r11.MergePrioritized(r1) r11.MergePrioritized(r5) r11.MergePrioritized(r3) r11.MergePrioritized(r8) r11.MergePrioritized(r2) Assert.True(r11.HasSymbol) Assert.Same(sym1, r11.SingleSymbol) Assert.True(r11.HasDiagnostic) Assert.True(r11.StopFurtherLookup) Dim diag11 = DirectCast(r11.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag11.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag11.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag11.AmbiguousSymbols.Item(2)) Dim r12 = New LookupResult() Dim r12Empty = New LookupResult() r12.MergePrioritized(r1) r12.MergePrioritized(r12Empty) Assert.False(r12.HasSymbol) Assert.False(r12.HasDiagnostic) Assert.False(r12.StopFurtherLookup) Dim r13 = New LookupResult() r13.MergePrioritized(r1) r13.MergePrioritized(r5) r13.MergePrioritized(r4) Assert.True(r13.HasSymbol) Assert.Same(sym2, r13.SingleSymbol) Assert.True(r13.HasDiagnostic) Assert.False(r13.StopFurtherLookup) Dim diag13 = DirectCast(r13.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag13.Code) Assert.Same(sym2, diag13.BadSymbol) Dim r14 = New LookupResult() r14.MergeAmbiguous(r1, AddressOf GenerateAmbiguity) r14.MergeAmbiguous(r5, AddressOf GenerateAmbiguity) r14.MergeAmbiguous(r4, AddressOf GenerateAmbiguity) Assert.True(r14.HasSymbol) Assert.Same(sym2, r14.SingleSymbol) Assert.True(r14.HasDiagnostic) Assert.False(r14.StopFurtherLookup) Dim diag14 = DirectCast(r14.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag14.Code) Assert.Same(sym2, diag14.BadSymbol) Dim r15 = New LookupResult() r15.MergeAmbiguous(r1, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r8, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r3, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r14, AddressOf GenerateAmbiguity) Assert.True(r15.HasSymbol) Assert.Same(sym4, r15.SingleSymbol) Assert.True(r15.HasDiagnostic) Assert.True(r15.StopFurtherLookup) Dim diag15 = DirectCast(r15.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym4, diag15.AmbiguousSymbols.Item(0)) Assert.Same(sym1, diag15.AmbiguousSymbols.Item(1)) Assert.Same(sym2, diag15.AmbiguousSymbols.Item(2)) Assert.Same(sym3, diag15.AmbiguousSymbols.Item(3)) Dim r16 = SingleLookupResult.Good(meth1) Dim r17 = SingleLookupResult.Good(meth2) Dim r18 = SingleLookupResult.Good(meth3) Dim r19 = New LookupResult() r19.MergeMembersOfTheSameType(r16, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(1, r19.Symbols.Count) Assert.False(r19.HasDiagnostic) r19.MergeMembersOfTheSameType(r17, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(2, r19.Symbols.Count) Assert.False(r19.HasDiagnostic) r19.MergeMembersOfTheSameType(r18, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(3, r19.Symbols.Count) Assert.Equal(r16.Symbol, r19.Symbols(0)) Assert.Equal(r17.Symbol, r19.Symbols(1)) Assert.Equal(r18.Symbol, r19.Symbols(2)) Assert.False(r19.HasDiagnostic) r19.MergeAmbiguous(r2, AddressOf GenerateAmbiguity) Assert.True(r19.StopFurtherLookup) Assert.Equal(1, r19.Symbols.Count) Assert.Equal(r16.Symbol, r19.SingleSymbol) Assert.True(r19.HasDiagnostic) Dim diag19 = DirectCast(r19.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Equal(4, diag19.AmbiguousSymbols.Length) Assert.Equal(r16.Symbol, diag19.AmbiguousSymbols(0)) Assert.Equal(r17.Symbol, diag19.AmbiguousSymbols(1)) Assert.Equal(r18.Symbol, diag19.AmbiguousSymbols(2)) Assert.Equal(r2.Symbol, diag19.AmbiguousSymbols(3)) End Sub Private Function GenerateAmbiguity(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, New FormattedSymbolList(syms.AsEnumerable)) End Function <Fact()> Public Sub MemberLookup1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Comp"> <file name="a.vb"> Option Strict On Option Explicit On Class A Public Class M3(Of T) End Class Public Overloads Sub M4(ByVal x As Integer, ByVal y As Integer) End Sub Public Overloads Sub M5(ByVal x As Integer, ByVal y As Integer) End Sub End Class Class B Inherits A Public Shared Sub M1(Of T)() End Sub Public Shared Sub M2() End Sub Public Shadows M3 As Integer Public Overloads Sub M4(ByVal x As Integer, ByVal y As String) End Sub Public Shadows Sub M5(ByVal x As Integer, ByVal y As String) End Sub End Class Class C Inherits B Public Shadows Class M1 End Class Public Shadows Class M2(Of T) End Class Public Overloads Sub M4() End Sub Public Overloads Sub M4(ByVal x As Integer) End Sub Public Overloads Sub M5() End Sub Public Overloads Sub M5(ByVal x As Integer) End Sub End Class Module Module1 Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) Dim context = GetContext(compilation, "a.vb", "Sub Main") Dim globalNS = compilation.GlobalNamespace Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol) Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol) Dim classC = DirectCast(globalNS.GetMembers("C").Single(), NamedTypeSymbol) Dim classA_M3 = DirectCast(classA.GetMembers("M3").Single(), NamedTypeSymbol) Dim methA_M4 = DirectCast(classA.GetMembers("M4").Single(), MethodSymbol) Dim methA_M5 = DirectCast(classA.GetMembers("M5").Single(), MethodSymbol) Dim methB_M1 = DirectCast(classB.GetMembers("M1").Single(), MethodSymbol) Dim methB_M2 = DirectCast(classB.GetMembers("M2").Single(), MethodSymbol) Dim methB_M4 = DirectCast(classB.GetMembers("M4").Single(), MethodSymbol) Dim methB_M5 = DirectCast(classB.GetMembers("M5").Single(), MethodSymbol) Dim fieldB_M3 = DirectCast(classB.GetMembers("M3").Single(), FieldSymbol) Dim classC_M1 = DirectCast(classC.GetMembers("M1").Single(), NamedTypeSymbol) Dim classC_M2 = DirectCast(classC.GetMembers("M2").Single(), NamedTypeSymbol) Dim methC_M4_0 = DirectCast(classC.GetMembers("M4")(0), MethodSymbol) Dim methC_M4_1 = DirectCast(classC.GetMembers("M4")(1), MethodSymbol) Dim methC_M5_0 = DirectCast(classC.GetMembers("M5")(0), MethodSymbol) Dim methC_M5_1 = DirectCast(classC.GetMembers("M5")(1), MethodSymbol) Dim lr As LookupResult ' nothing found lr = New LookupResult() context.LookupMember(lr, classC, "fizzle", 0, Nothing, Nothing) Assert.Equal(LookupResultKind.Empty, lr.Kind) ' non-generic class shadows with arity 0 lr = New LookupResult() context.LookupMember(lr, classC, "M1", 0, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(classC_M1, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' method found with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M1", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(methB_M1, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' generic class shadows with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M2", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(classC_M2, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' method found with arity 0 lr = New LookupResult() context.LookupMember(lr, classC, "M2", 0, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(methB_M2, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' field shadows with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M3", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(fieldB_M3, lr.Symbols.Single()) Assert.True(lr.HasDiagnostic) ' should collection all overloads of M4 lr = New LookupResult() context.LookupMember(lr, classC, "M4", 1, LookupOptions.AllMethodsOfAnyArity, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(4, lr.Symbols.Count) Assert.Contains(methA_M4, lr.Symbols) Assert.Contains(methB_M4, lr.Symbols) Assert.Contains(methC_M4_0, lr.Symbols) Assert.Contains(methC_M4_1, lr.Symbols) Assert.False(lr.HasDiagnostic) ' shouldn't get A.M5 because B.M5 is marked Shadows lr = New LookupResult() context.LookupMember(lr, classC, "M5", 1, LookupOptions.AllMethodsOfAnyArity, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(3, lr.Symbols.Count) Assert.DoesNotContain(methA_M5, lr.Symbols) Assert.Contains(methB_M5, lr.Symbols) Assert.Contains(methC_M5_0, lr.Symbols) Assert.Contains(methC_M5_1, lr.Symbols) Assert.False(lr.HasDiagnostic) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact()> Public Sub Bug3024() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3024"> <file name="a.vb"> Imports P Imports R Module C Dim x As Q End Module Namespace R Module M Class Q End Class End Module End Namespace Namespace P.Q End Namespace </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("R.M+Q"), compilation.GetTypeByMetadataName("C").GetMembers("x").OfType(Of FieldSymbol)().Single().Type) End Sub <Fact()> Public Sub Bug3025() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3025"> <file name="a.vb"> Imports P Imports R Module C Dim x As Q End Module Namespace R Module M Class Q End Class End Module End Namespace Namespace P.Q Class Z End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30182: Type expected. Dim x As Q ~ </expected>) End Sub <Fact()> Public Sub Bug4099() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4099"> <file name="a.vb"> Imports N Imports K Namespace N Module M Class C End Class End Module End Namespace Namespace K Class C End Class End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("K.C"), compilation.GetTypeByMetadataName("A").BaseType) End Sub <Fact()> Public Sub Bug4100() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4100"> <file name="a.vb"> Imports N Imports K Namespace N Class C End Class End Namespace Namespace K Namespace C Class D End Class End Namespace End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType) compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4100"> <file name="a.vb"> Imports K Imports N Namespace N Class C End Class End Namespace Namespace K Namespace C Class D End Class End Namespace End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType) End Sub <Fact()> Public Sub Bug3015() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3015"> <file name="a.vb"> Imports P Imports R Module Module1 Sub Main() Dim x As Q = New Q() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace R Class Q End Class End Namespace Namespace P.Q End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ R.Q ]]>) End Sub <Fact()> Public Sub Bug3014() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3014"> <file name="a.vb"> Imports P = System Imports R Module C Sub Main() Dim x As P(Of Integer) x=Nothing End Sub End Module Namespace R Class P(Of T) End Class End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32045: 'System' has no type parameters and so cannot have type arguments. Dim x As P(Of Integer) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AmbiguityInImports() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguityInImports1"> <file name="a.vb"> Namespace NS1 Friend Class CT1 End Class Friend Class CT2 End Class Public Class CT3(Of T) End Class Public Class CT4 End Class Public Module M1 Friend Class CT1 End Class Public Class CT2(Of T) End Class Public Class CT3 End Class End Module Public Module M2 Public Class CT3 End Class End Module End Namespace Namespace NS2 Public Class CT5 End Class Public Module M3 Public Class CT5 End Class End Module End Namespace Namespace NS3 Public Class CT5 End Class End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguityInImports3"> <file name="a.vb"> Namespace NS1 Namespace CT4 End Namespace End Namespace Namespace NS2 Namespace CT5 End Namespace End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="AmbiguityInImports2"> <file name="a.vb"> Imports NS2 Imports NS3 Namespace NS1 Module Module1 Sub Test() Dim x1 As CT1 Dim x2 As CT2 Dim x3 As CT3 Dim x4 As CT4 Dim x5 As CT5 x1 = Nothing x2 = Nothing x3 = Nothing x4 = Nothing x5 = Nothing End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC30389: 'NS1.CT1' is not accessible in this context because it is 'Friend'. Dim x1 As CT1 ~~~ BC30389: 'NS1.CT2' is not accessible in this context because it is 'Friend'. Dim x2 As CT2 ~~~ BC30562: 'CT3' is ambiguous between declarations in Modules 'NS1.M1, NS1.M2'. Dim x3 As CT3 ~~~ BC30560: 'CT4' is ambiguous in the namespace 'NS1'. Dim x4 As CT4 ~~~ BC30560: 'CT5' is ambiguous in the namespace 'NS2'. Dim x5 As CT5 ~~~ </expected>) End Sub <Fact()> Public Sub TieBreakingInImports() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports1"> <file name="a.vb"> Namespace NS1 Namespace Test1 Public Class Test3 End Class End Namespace Public Class Test2 End Class Public Class Test5 End Class End Namespace Namespace NS2 Namespace Test1 Public Class Test4 End Class End Namespace Public Class Test5 End Class End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports2"> <file name="a.vb"> Namespace NS3 Class Test1 End Class Class Test1(Of T) End Class Class Test5 End Class End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports3"> <file name="a.vb"> Namespace NS2 Class Test2(Of T) End Class End Namespace </file> </compilation>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation4, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS2 Imports NS3 Imports NS1 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation5, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS2, NS1'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) Dim compilation6 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS3 Imports NS1 Imports NS2 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation6, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) End Sub <Fact()> Public Sub RecursiveCheckForAccessibleTypesWithinANamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveCheckForAccessibleTypesWithinANamespace1"> <file name="a.vb"> Imports P Module Module1 Sub Main() Dim x As Q.R.S = New Q.R.S() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace P Namespace Q Namespace R Public Class S End Class End Namespace End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ P.Q.R.S ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveCheckForAccessibleTypesWithinANamespace2"> <file name="a.vb"> Imports P Module Module1 Sub Main() Dim x As Q.R.S = New Q.R.S() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace P Namespace Q Namespace R Friend Class S End Class Friend Class T End Class End Namespace End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ P.Q.R.S ]]>) End Sub <Fact()> Public Sub DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace() ' We need to be careful about metadata references we use here. ' The test checks that fields of namespace symbols are initialized in certain order. ' If we used a shared Mscorlib reference then other tests might have already initialized it's shared AssemblySymbol. Dim nonSharedMscorlibReference = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display:="mscorlib.v4_0_30319.dll") Dim c = VisualBasicCompilation.Create("DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace", syntaxTrees:={Parse(<text> Namespace P End Namespace </text>.Value)}, references:={nonSharedMscorlibReference}) Dim system = c.Assembly.Modules(0).GetReferencedAssemblySymbols()(0).GlobalNamespace.GetMembers("System").OfType(Of PENamespaceSymbol)().Single() Dim deployment = system.GetMembers("Deployment").OfType(Of PENamespaceSymbol)().Single() Dim internal = deployment.GetMembers("Internal").OfType(Of PENamespaceSymbol)().Single() Dim isolation = internal.GetMembers("Isolation").OfType(Of PENamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolation.AreTypesLoaded) Assert.Equal(Accessibility.Friend, isolation.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolation.AreTypesLoaded) Assert.Equal(Accessibility.Friend, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) isolation.GetTypeMembers() Assert.True(isolation.AreTypesLoaded) Dim io = system.GetMembers("IO").OfType(Of PENamespaceSymbol)().Single() Dim isolatedStorage = io.GetMembers("IsolatedStorage").OfType(Of PENamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolatedStorage.AreTypesLoaded) Assert.Equal(Accessibility.Public, isolatedStorage.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolatedStorage.AreTypesLoaded) Assert.Equal(Accessibility.Public, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) End Sub <Fact()> Public Sub TestMergedNamespaceContainsTypesAccessibleFrom() Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C1"> <file name="a.vb"> Namespace P Namespace Q Public Class R End Class End Namespace End Namespace </file> </compilation>) Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C2"> <file name="a.vb"> Namespace P Namespace Q Friend Class S End Class End Namespace End Namespace </file> </compilation>) Dim c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C3"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2)}) Dim p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() Dim q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) Assert.Equal(Accessibility.Public, q.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C3"> <file name="a.vb"> Namespace P Namespace Q Friend Class U End Class End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c2)}) p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.True, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.True, q.RawContainsAccessibleTypes) Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Dim c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C4"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)}) p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes) Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes) c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C4"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)}) p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.Equal(Accessibility.Friend, q.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Friend, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes) Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes) End Sub <Fact()> Public Sub Bug4128() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4128"> <file name="a.vb"> Imports A = C.B Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 Imports XXXXYYY = UNKNOWN(Of UNKNOWN) Module X Class C End Class End Module Module Y Class C End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30562: 'C' is ambiguous between declarations in Modules 'X, Y'. Imports A = C.B ~ BC40056: Namespace or type specified in the Imports 'UNKNOWN.UNKNOWN' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'UNKNOWN' is not defined. Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 ~~~~~~~ BC40056: Namespace or type specified in the Imports 'UNKNOWN' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports XXXXYYY = UNKNOWN(Of UNKNOWN) ~~~~~~~~~~~~~~~~~~~ BC30002: Type 'UNKNOWN' is not defined. Imports XXXXYYY = UNKNOWN(Of UNKNOWN) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub Bug4220() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4220"> <file name="a.vb"> Imports A Imports A.B Imports A.B Namespace A Module B End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31051: Namespace or type 'B' has already been imported. Imports A.B ~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4220"> <file name="a.vb"> Imports A Imports A.B Module Module1 Sub Main() c() End Sub End Module Namespace A Module B Public Sub c() System.Console.WriteLine("Sub c()") End Sub End Module End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ Sub c() ]]>) End Sub <Fact()> Public Sub Bug4180() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4180"> <file name="a.vb"> Namespace System Class [Object] End Class Class C Inherits [Object] End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) Assert.Same(compilation.Assembly.GetTypeByMetadataName("System.Object"), compilation.GetTypeByMetadataName("System.C").BaseType) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C1"> <file name="a.vb"> Namespace NS1 Namespace NS2 Public Class C1 End Class End Namespace End Namespace Namespace NS5 Public Module Module3 Public Sub Test() End Sub End Module End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C2"> <file name="a.vb"> Namespace NS1 Namespace NS2 Namespace C1 Public Class C2 End Class End Namespace End Namespace End Namespace Namespace NS5 Public Module Module4 Public Sub Test() End Sub End Module End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS1 Module Module1 Sub Main() Dim x As NS2.C1.C2 = New NS2.C1.C2() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace NS2 Namespace C1 End Namespace End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation3, <![CDATA[ NS1.NS2.C1.C2 ]]>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C4"> <file name="a.vb"> Namespace NS1 Namespace NS2 Namespace C1 Public Class C3 End Class End Namespace End Namespace End Namespace </file> </compilation>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Imports NS1 Module Module1 Sub Main() Dim x As NS2.C1.C2 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation4)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation3, <expected> BC30560: 'C1' is ambiguous in the namespace 'NS1.NS2'. Dim x As NS2.C1.C2 = Nothing ~~~~~~ </expected>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS5 Module Module1 Sub Main() Test() End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation3, <expected> BC30562: 'Test' is ambiguous between declarations in Modules 'NS5.Module3, NS5.Module4'. Test() ~~~~ </expected>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS5 Module Module1 Sub Main() Test() End Sub End Module Module Module2 Sub Test() System.Console.WriteLine("Module2.Test") End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation3, <![CDATA[ Module2.Test ]]>) End Sub <Fact()> Public Sub Bug4817() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports A Imports B Class A Shared Sub Goo() System.Console.WriteLine("A.Goo()") End Sub End Class Class B Inherits A End Class Module C Sub Main() Goo() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ A.Goo() ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports A Imports B Class A Shared Sub Goo() System.Console.WriteLine("A.Goo()") End Sub End Class Class B Inherits A Overloads Shared Sub Goo(x As Integer) System.Console.WriteLine("B.Goo()") End Sub End Class Module C Sub Main() Goo() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30561: 'Goo' is ambiguous, imported from the namespaces or types 'A, B, A'. Goo() ~~~ </expected>) End Sub <Fact()> Public Sub LookupOptionMustBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Explicit On Interface I Sub GooInstance() End Interface Class A Public Shared Sub GooShared() End Sub Public Sub GooInstance() End Sub End Class Module Module1 Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) Dim context = GetContext(compilation, "a.vb", "Sub Main") Dim globalNS = compilation.GlobalNamespace Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol) Dim gooShared = DirectCast(classA.GetMembers("GooShared").Single(), MethodSymbol) Dim gooInstance = DirectCast(classA.GetMembers("GooInstance").Single(), MethodSymbol) Dim lr As LookupResult ' Find Shared member lr = New LookupResult() context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustNotBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(gooShared, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) lr = New LookupResult() context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustNotBeInstance, Nothing) Assert.Equal(LookupResultKind.MustNotBeInstance, lr.Kind) Assert.True(lr.HasDiagnostic) 'error BC30469: Reference to a non-shared member requires an object reference. lr = New LookupResult() context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(gooInstance, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) lr = New LookupResult() context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(LookupResultKind.MustBeInstance, lr.Kind) Assert.False(lr.HasDiagnostic) Dim interfaceI = DirectCast(globalNS.GetMembers("I").Single(), NamedTypeSymbol) Dim ifooInstance = DirectCast(interfaceI.GetMembers("GooInstance").Single(), MethodSymbol) lr = New LookupResult() context.LookupMember(lr, interfaceI, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(ifooInstance, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> <WorkItem(545575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545575")> Public Sub Bug14079() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Interface I Class Goo Shared Sub Boo() End Sub End Class End Interface Class D Sub Goo() End Sub Interface I2 Inherits I Shadows Class Goo(Of T) End Class Class C Sub Bar() Goo.Boo() End Sub End Class End Interface End Class </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) End Sub <Fact(), WorkItem(531293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531293")> Public Sub Bug17900() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports Undefined Module Program Event E Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40056: Namespace or type specified in the Imports 'Undefined' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Undefined ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AmbiguousNamespaces_01() Dim compilation = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Imports System Imports System.Windows.Forms Module Module1 Sub Main() Dim x As ComponentModel.INotifyPropertyChanged = Nothing 'BIND1:"ComponentModel" End Sub End Module </file> </compilation>, references:={Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic, Net451.SystemWindowsForms}) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info = semanticModel.GetSymbolInfo(node) Dim ns = DirectCast(info.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns.NamespaceKind) Assert.Equal("System.ComponentModel", ns.ToTestDisplayString()) Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"}, semanticModel.LookupNamespacesAndTypes(node.Position, name:="ComponentModel").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"}, semanticModel.LookupSymbols(node.Position, name:="ComponentModel").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports Windows.Foundation Module Module1 Sub Main() Diagnostics.Debug.WriteLine("") 'BIND1:"Diagnostics" Dim x = Diagnostics Diagnostics End Sub End Module </file> </compilation>, WinRtRefs) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'Diagnostics' is a namespace and cannot be used as an expression. Dim x = Diagnostics ~~~~~~~~~~~ BC30112: 'Diagnostics' is a namespace and cannot be used as an expression. Diagnostics ~~~~~~~~~~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info = semanticModel.GetSymbolInfo(node) Dim ns = DirectCast(info.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind) Assert.Equal("System.Diagnostics", ns.ToTestDisplayString()) Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"}, semanticModel.LookupNamespacesAndTypes(node.Position, name:="Diagnostics").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"}, semanticModel.LookupSymbols(node.Position, name:="Diagnostics").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Module Module1 Sub Main() NS3. 'BIND1:"NS3" NS4.T1.M1() 'BIND2:"NS4" End Sub End Module Namespace NS1 Namespace NS3 Namespace NS4 Class T1 Shared Sub M1() End Sub End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS3 Namespace NS4 Class T2 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Dim ns2 = DirectCast(info2.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns2.NamespaceKind) Assert.Equal("NS1.NS3.NS4", ns2.ToTestDisplayString()) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Dim ns1 = DirectCast(info1.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns1.NamespaceKind) Assert.Equal("NS1.NS3", ns1.ToTestDisplayString()) Assert.Equal({"NS1.NS3", "NS2.NS3"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS3").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS3", "NS2.NS3"}, semanticModel.LookupSymbols(node1.Position, name:="NS3").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS4 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = GetType(NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1) 'BIND3:"T1" End Sub Class Test1 Inherits NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" End Class Sub Main2() Dim x = NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1. 'BIND9:"T1" M1() End Sub Sub Main3() Dim x = GetType(NS6) 'BIND10:"NS6" Dim y = GetType(NS6. 'BIND11:"NS6" NS7) 'BIND12:"NS7" End Sub Class Test2 Inherits NS6 'BIND13:"NS6" End Class Class Test3 Inherits NS6. 'BIND14:"NS6" NS7 'BIND15:"NS7" End Class Sub Main4() NS6 'BIND16:"NS6" NS6. 'BIND17:"NS6" NS7 'BIND18:"NS7" End Sub <NS6> 'BIND19:"NS6" <NS6. 'BIND20:"NS6" NS7> 'BIND21:"NS7" <NS6. 'BIND22:"NS6" NS7. 'BIND23:"NS7" T1> 'BIND24:"T1" Class Test4 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS4 Namespace NS6 Namespace NS7 Namespace T1 Class T2 End Class End Namespace End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Dim x = GetType(NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Inherits NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Dim x = NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30182: Type expected. Dim x = GetType(NS6) 'BIND10:"NS6" ~~~ BC30182: Type expected. Dim y = GetType(NS6. 'BIND11:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. Inherits NS6 'BIND13:"NS6" ~~~ BC30182: Type expected. Inherits NS6. 'BIND14:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30112: 'NS6' is a namespace and cannot be used as an expression. NS6 'BIND16:"NS6" ~~~ BC30112: 'NS6.NS7' is a namespace and cannot be used as an expression. NS6. 'BIND17:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. <NS6> 'BIND19:"NS6" ~~~ BC30182: Type expected. <NS6. 'BIND20:"NS6" ~~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. <NS6. 'BIND22:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(24) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 24} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7.T1", "NS2.NS6.NS7.T1", "NS4.NS6.NS7.T1", "NS5.NS6.NS7.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 23} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 22} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {10, 13, 16, 19} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(If(i = 16, CandidateReason.Ambiguous, If(i = 19, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info2.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {12, 15, 18, 21} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(If(i = 18, CandidateReason.Ambiguous, If(i = 21, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7", "NS9.NS6.NS7"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {11, 14, 17, 20} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_05() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS4 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = GetType(NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1) 'BIND3:"T1" End Sub Class Test1 Inherits NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" End Class Sub Main2() NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1. 'BIND9:"T1" M1() End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Class T1 Inherits System.Attribute Shared Sub M1() End Sub End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Class T2 End Class End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS4 Namespace NS6 Namespace NS7 Namespace T4 Class T2 End Class End Namespace End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7.T1", info3.Symbol.ToTestDisplayString()) Next Dim info12 = semanticModel.GetSymbolInfo(nodes(12)) Assert.Equal("Sub NS1.NS6.NS7.T1..ctor()", info12.Symbol.ToTestDisplayString()) For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_06() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" Dim y = GetType(NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" M1) 'BIND6:"M1" End Sub <NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" M1> 'BIND9:"M1" Class Test1 Inherits NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" M1 'BIND12:"M1" End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30562: 'M1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.T1, NS2.NS6.NS7.T1, NS5.NS6.NS7.T1'. Dim x = NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. Dim y = GetType(NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. <NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. Inherits NS6. 'BIND10:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 12} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(If(i = 3, CandidateReason.Ambiguous, CandidateReason.NotATypeOrNamespace), info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"Sub NS1.NS6.NS7.T1.M1()", "Sub NS2.NS6.NS7.T1.M1()", "Sub NS5.NS6.NS7.T1.M1()"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_07() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" End Sub End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1(x as Integer) End Sub Sub M1(x as Long) End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'M1' accepts this number of arguments. M1() 'BIND3:"M1" ~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim info3 = semanticModel.GetSymbolInfo(node3) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, info3.CandidateReason) Assert.Equal({"Sub NS1.NS6.NS7.T1.M1(x As System.Int32)", "Sub NS1.NS6.NS7.T1.M1(x As System.Int64)"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_08() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" End Sub End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim info3 = semanticModel.GetSymbolInfo(node3) Assert.Equal("Sub NS1.NS6.NS7.T1.M1()", info3.Symbol.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_09() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Class Test1 Inherits NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1 'BIND3:"T1" End Class Sub Main() NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" Dim x = GetType(NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1) 'BIND9:"T1" End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. Inherits NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. Dim x = GetType(NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. <NS6. 'BIND10:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 12} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7.Module1.T1", "NS2.NS6.NS7.Module1.T1", "NS5.NS6.NS7.Module1.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Class Test1 Inherits NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1 'BIND3:"T1" End Class Sub Main() NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" Dim x = GetType(NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1) 'BIND9:"T1" End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module Module1 Class T1 Inherits System.Attribute End Class End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30109: 'Module1.T1' is a class type and cannot be used as an expression. NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7.Module1.T1", info3.Symbol.ToTestDisplayString()) Next Dim info12 = semanticModel.GetSymbolInfo(nodes(12)) Assert.Equal("Sub NS1.NS6.NS7.Module1.T1..ctor()", info12.Symbol.ToTestDisplayString()) For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> <WorkItem(842056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842056")> Public Sub AmbiguousNamespaces_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class C End Class End Namespace Module M Dim c As X.C End Module ]]></file> </compilation>, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC37229: 'C' is ambiguous between declarations in namespaces 'A.X, B.X'. Dim c As X.C ~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants01() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants01b() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, DATETIME = DateTime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.Datetime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02b() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime, DATETIME, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02c() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, [System.Obsolete] DATETIME, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02d() Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum", <![CDATA[ Public Enum Color Red Green DateTime <System.Obsolete> Datetime = DateTime DATETIME Blue End Enum ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(vbCompilation1, <expected><![CDATA[ BC31421: 'Datetime' is already declared in this enum. <System.Obsolete> Datetime = DateTime ~~~~~~~~ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. <System.Obsolete> Datetime = DateTime ~~~~~~~~ BC31421: 'DATETIME' is already declared in this enum. DATETIME ~~~~~~~~ ]]></expected>) Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02e() Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum", <![CDATA[ Public Enum Color Red Green DateTime <System.Obsolete> Datetime = 2 Blue End Enum ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(vbCompilation1, <expected><![CDATA[ BC31421: 'Datetime' is already declared in this enum. <System.Obsolete> Datetime = 2 ~~~~~~~~ ]]></expected>) Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ ]]></expected>) CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class LookupTests Inherits BasicTestBase Private Function GetContext(compilation As VisualBasicCompilation, treeName As String, textToFind As String) As Binder Dim tree As SyntaxTree = CompilationUtils.GetTree(compilation, treeName) Dim position = CompilationUtils.FindPositionFromText(tree, textToFind) Return DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel).GetEnclosingBinder(position) End Function <Fact()> Public Sub TestLookupResult() Dim sym1 = New MockAssemblySymbol("hello") ' just a symbol to put in results Dim sym2 = New MockAssemblySymbol("goodbye") ' just a symbol to put in results Dim sym3 = New MockAssemblySymbol("world") ' just a symbol to put in results Dim sym4 = New MockAssemblySymbol("banana") ' just a symbol to put in results Dim sym5 = New MockAssemblySymbol("apple") ' just a symbol to put in results Dim meth1 = New MockMethodSymbol("goo") ' just a symbol to put in results Dim meth2 = New MockMethodSymbol("bag") ' just a symbol to put in results Dim meth3 = New MockMethodSymbol("baz") ' just a symbol to put in results Dim r1 = New LookupResult() r1.SetFrom(SingleLookupResult.Empty) Assert.False(r1.HasSymbol) Assert.False(r1.IsGood) Assert.False(r1.HasDiagnostic) Assert.False(r1.StopFurtherLookup) Dim r2 = SingleLookupResult.Good(sym1) Dim _r2 = New LookupResult() _r2.SetFrom(r2) Assert.True(_r2.HasSymbol) Assert.True(_r2.IsGood) Assert.Same(sym1, _r2.SingleSymbol) Assert.False(_r2.HasDiagnostic) Assert.True(_r2.StopFurtherLookup) Dim r3 = New LookupResult() r3.SetFrom(SingleLookupResult.Ambiguous(ImmutableArray.Create(Of Symbol)(sym1, sym2, sym3), AddressOf GenerateAmbiguity)) Assert.True(r3.HasSymbol) Assert.False(r3.IsGood) Assert.Same(sym1, r3.SingleSymbol) Assert.True(r3.HasDiagnostic) Assert.True(r3.StopFurtherLookup) Dim diag3 = DirectCast(r3.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag3.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag3.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag3.AmbiguousSymbols.Item(2)) Dim r4 = New LookupResult() r4.SetFrom(SingleLookupResult.Inaccessible(sym2, New BadSymbolDiagnostic(sym2, ERRID.ERR_InaccessibleSymbol2, sym2))) Assert.True(r4.HasSymbol) Assert.False(r4.IsGood) Assert.Same(sym2, r4.SingleSymbol) Assert.True(r4.HasDiagnostic) Assert.False(r4.StopFurtherLookup) Dim diag4 = DirectCast(r4.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag4.Code) Assert.Same(sym2, diag4.BadSymbol) Dim r5 = New LookupResult() r5.SetFrom(SingleLookupResult.WrongArity(sym3, ERRID.ERR_IndexedNotArrayOrProc)) Assert.True(r5.HasSymbol) Assert.False(r5.IsGood) Assert.Same(sym3, r5.SingleSymbol) Assert.True(r5.HasDiagnostic) Assert.False(r5.StopFurtherLookup) Dim diag5 = r5.Diagnostic Assert.Equal(ERRID.ERR_IndexedNotArrayOrProc, diag5.Code) Dim r6 = New LookupResult() r6.MergePrioritized(r1) r6.MergePrioritized(r2) Assert.True(r6.HasSymbol) Assert.Same(sym1, r6.SingleSymbol) Assert.False(r6.HasDiagnostic) Assert.True(r6.StopFurtherLookup) r6.Free() Dim r7 = New LookupResult() r7.MergePrioritized(r2) r7.MergePrioritized(r1) Assert.True(r7.HasSymbol) Assert.Same(sym1, r7.SingleSymbol) Assert.False(r7.HasDiagnostic) Assert.True(r7.StopFurtherLookup) Dim r8 = New LookupResult() r8.SetFrom(SingleLookupResult.Good(sym4)) Dim r9 = New LookupResult() r9.SetFrom(r2) r9.MergePrioritized(r8) Assert.True(r9.HasSymbol) Assert.Same(sym1, r9.SingleSymbol) Assert.False(r9.HasDiagnostic) Assert.True(r9.StopFurtherLookup) Dim r10 = New LookupResult() r10.SetFrom(r3) r10.MergePrioritized(r8) r10.MergePrioritized(r2) Assert.True(r10.HasSymbol) Assert.Same(sym1, r10.SingleSymbol) Assert.True(r10.HasDiagnostic) Assert.True(r10.StopFurtherLookup) Dim diag10 = DirectCast(r10.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag10.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag10.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag10.AmbiguousSymbols.Item(2)) Dim r11 = New LookupResult() r11.MergePrioritized(r1) r11.MergePrioritized(r5) r11.MergePrioritized(r3) r11.MergePrioritized(r8) r11.MergePrioritized(r2) Assert.True(r11.HasSymbol) Assert.Same(sym1, r11.SingleSymbol) Assert.True(r11.HasDiagnostic) Assert.True(r11.StopFurtherLookup) Dim diag11 = DirectCast(r11.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym1, diag11.AmbiguousSymbols.Item(0)) Assert.Same(sym2, diag11.AmbiguousSymbols.Item(1)) Assert.Same(sym3, diag11.AmbiguousSymbols.Item(2)) Dim r12 = New LookupResult() Dim r12Empty = New LookupResult() r12.MergePrioritized(r1) r12.MergePrioritized(r12Empty) Assert.False(r12.HasSymbol) Assert.False(r12.HasDiagnostic) Assert.False(r12.StopFurtherLookup) Dim r13 = New LookupResult() r13.MergePrioritized(r1) r13.MergePrioritized(r5) r13.MergePrioritized(r4) Assert.True(r13.HasSymbol) Assert.Same(sym2, r13.SingleSymbol) Assert.True(r13.HasDiagnostic) Assert.False(r13.StopFurtherLookup) Dim diag13 = DirectCast(r13.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag13.Code) Assert.Same(sym2, diag13.BadSymbol) Dim r14 = New LookupResult() r14.MergeAmbiguous(r1, AddressOf GenerateAmbiguity) r14.MergeAmbiguous(r5, AddressOf GenerateAmbiguity) r14.MergeAmbiguous(r4, AddressOf GenerateAmbiguity) Assert.True(r14.HasSymbol) Assert.Same(sym2, r14.SingleSymbol) Assert.True(r14.HasDiagnostic) Assert.False(r14.StopFurtherLookup) Dim diag14 = DirectCast(r14.Diagnostic, BadSymbolDiagnostic) Assert.Equal(ERRID.ERR_InaccessibleSymbol2, diag14.Code) Assert.Same(sym2, diag14.BadSymbol) Dim r15 = New LookupResult() r15.MergeAmbiguous(r1, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r8, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r3, AddressOf GenerateAmbiguity) r15.MergeAmbiguous(r14, AddressOf GenerateAmbiguity) Assert.True(r15.HasSymbol) Assert.Same(sym4, r15.SingleSymbol) Assert.True(r15.HasDiagnostic) Assert.True(r15.StopFurtherLookup) Dim diag15 = DirectCast(r15.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Same(sym4, diag15.AmbiguousSymbols.Item(0)) Assert.Same(sym1, diag15.AmbiguousSymbols.Item(1)) Assert.Same(sym2, diag15.AmbiguousSymbols.Item(2)) Assert.Same(sym3, diag15.AmbiguousSymbols.Item(3)) Dim r16 = SingleLookupResult.Good(meth1) Dim r17 = SingleLookupResult.Good(meth2) Dim r18 = SingleLookupResult.Good(meth3) Dim r19 = New LookupResult() r19.MergeMembersOfTheSameType(r16, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(1, r19.Symbols.Count) Assert.False(r19.HasDiagnostic) r19.MergeMembersOfTheSameType(r17, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(2, r19.Symbols.Count) Assert.False(r19.HasDiagnostic) r19.MergeMembersOfTheSameType(r18, False) Assert.True(r19.StopFurtherLookup) Assert.Equal(3, r19.Symbols.Count) Assert.Equal(r16.Symbol, r19.Symbols(0)) Assert.Equal(r17.Symbol, r19.Symbols(1)) Assert.Equal(r18.Symbol, r19.Symbols(2)) Assert.False(r19.HasDiagnostic) r19.MergeAmbiguous(r2, AddressOf GenerateAmbiguity) Assert.True(r19.StopFurtherLookup) Assert.Equal(1, r19.Symbols.Count) Assert.Equal(r16.Symbol, r19.SingleSymbol) Assert.True(r19.HasDiagnostic) Dim diag19 = DirectCast(r19.Diagnostic, AmbiguousSymbolDiagnostic) Assert.Equal(4, diag19.AmbiguousSymbols.Length) Assert.Equal(r16.Symbol, diag19.AmbiguousSymbols(0)) Assert.Equal(r17.Symbol, diag19.AmbiguousSymbols(1)) Assert.Equal(r18.Symbol, diag19.AmbiguousSymbols(2)) Assert.Equal(r2.Symbol, diag19.AmbiguousSymbols(3)) End Sub Private Function GenerateAmbiguity(syms As ImmutableArray(Of Symbol)) As AmbiguousSymbolDiagnostic Return New AmbiguousSymbolDiagnostic(ERRID.ERR_AmbiguousInModules2, syms, New FormattedSymbolList(syms.AsEnumerable)) End Function <Fact()> Public Sub MemberLookup1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Comp"> <file name="a.vb"> Option Strict On Option Explicit On Class A Public Class M3(Of T) End Class Public Overloads Sub M4(ByVal x As Integer, ByVal y As Integer) End Sub Public Overloads Sub M5(ByVal x As Integer, ByVal y As Integer) End Sub End Class Class B Inherits A Public Shared Sub M1(Of T)() End Sub Public Shared Sub M2() End Sub Public Shadows M3 As Integer Public Overloads Sub M4(ByVal x As Integer, ByVal y As String) End Sub Public Shadows Sub M5(ByVal x As Integer, ByVal y As String) End Sub End Class Class C Inherits B Public Shadows Class M1 End Class Public Shadows Class M2(Of T) End Class Public Overloads Sub M4() End Sub Public Overloads Sub M4(ByVal x As Integer) End Sub Public Overloads Sub M5() End Sub Public Overloads Sub M5(ByVal x As Integer) End Sub End Class Module Module1 Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) Dim context = GetContext(compilation, "a.vb", "Sub Main") Dim globalNS = compilation.GlobalNamespace Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol) Dim classB = DirectCast(globalNS.GetMembers("B").Single(), NamedTypeSymbol) Dim classC = DirectCast(globalNS.GetMembers("C").Single(), NamedTypeSymbol) Dim classA_M3 = DirectCast(classA.GetMembers("M3").Single(), NamedTypeSymbol) Dim methA_M4 = DirectCast(classA.GetMembers("M4").Single(), MethodSymbol) Dim methA_M5 = DirectCast(classA.GetMembers("M5").Single(), MethodSymbol) Dim methB_M1 = DirectCast(classB.GetMembers("M1").Single(), MethodSymbol) Dim methB_M2 = DirectCast(classB.GetMembers("M2").Single(), MethodSymbol) Dim methB_M4 = DirectCast(classB.GetMembers("M4").Single(), MethodSymbol) Dim methB_M5 = DirectCast(classB.GetMembers("M5").Single(), MethodSymbol) Dim fieldB_M3 = DirectCast(classB.GetMembers("M3").Single(), FieldSymbol) Dim classC_M1 = DirectCast(classC.GetMembers("M1").Single(), NamedTypeSymbol) Dim classC_M2 = DirectCast(classC.GetMembers("M2").Single(), NamedTypeSymbol) Dim methC_M4_0 = DirectCast(classC.GetMembers("M4")(0), MethodSymbol) Dim methC_M4_1 = DirectCast(classC.GetMembers("M4")(1), MethodSymbol) Dim methC_M5_0 = DirectCast(classC.GetMembers("M5")(0), MethodSymbol) Dim methC_M5_1 = DirectCast(classC.GetMembers("M5")(1), MethodSymbol) Dim lr As LookupResult ' nothing found lr = New LookupResult() context.LookupMember(lr, classC, "fizzle", 0, Nothing, Nothing) Assert.Equal(LookupResultKind.Empty, lr.Kind) ' non-generic class shadows with arity 0 lr = New LookupResult() context.LookupMember(lr, classC, "M1", 0, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(classC_M1, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' method found with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M1", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(methB_M1, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' generic class shadows with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M2", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(classC_M2, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' method found with arity 0 lr = New LookupResult() context.LookupMember(lr, classC, "M2", 0, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(methB_M2, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) ' field shadows with arity 1 lr = New LookupResult() context.LookupMember(lr, classC, "M3", 1, Nothing, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(fieldB_M3, lr.Symbols.Single()) Assert.True(lr.HasDiagnostic) ' should collection all overloads of M4 lr = New LookupResult() context.LookupMember(lr, classC, "M4", 1, LookupOptions.AllMethodsOfAnyArity, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(4, lr.Symbols.Count) Assert.Contains(methA_M4, lr.Symbols) Assert.Contains(methB_M4, lr.Symbols) Assert.Contains(methC_M4_0, lr.Symbols) Assert.Contains(methC_M4_1, lr.Symbols) Assert.False(lr.HasDiagnostic) ' shouldn't get A.M5 because B.M5 is marked Shadows lr = New LookupResult() context.LookupMember(lr, classC, "M5", 1, LookupOptions.AllMethodsOfAnyArity, Nothing) Assert.True(lr.StopFurtherLookup) Assert.Equal(3, lr.Symbols.Count) Assert.DoesNotContain(methA_M5, lr.Symbols) Assert.Contains(methB_M5, lr.Symbols) Assert.Contains(methC_M5_0, lr.Symbols) Assert.Contains(methC_M5_1, lr.Symbols) Assert.False(lr.HasDiagnostic) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact()> Public Sub Bug3024() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3024"> <file name="a.vb"> Imports P Imports R Module C Dim x As Q End Module Namespace R Module M Class Q End Class End Module End Namespace Namespace P.Q End Namespace </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("R.M+Q"), compilation.GetTypeByMetadataName("C").GetMembers("x").OfType(Of FieldSymbol)().Single().Type) End Sub <Fact()> Public Sub Bug3025() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3025"> <file name="a.vb"> Imports P Imports R Module C Dim x As Q End Module Namespace R Module M Class Q End Class End Module End Namespace Namespace P.Q Class Z End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30182: Type expected. Dim x As Q ~ </expected>) End Sub <Fact()> Public Sub Bug4099() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4099"> <file name="a.vb"> Imports N Imports K Namespace N Module M Class C End Class End Module End Namespace Namespace K Class C End Class End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("K.C"), compilation.GetTypeByMetadataName("A").BaseType) End Sub <Fact()> Public Sub Bug4100() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4100"> <file name="a.vb"> Imports N Imports K Namespace N Class C End Class End Namespace Namespace K Namespace C Class D End Class End Namespace End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType) compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4100"> <file name="a.vb"> Imports K Imports N Namespace N Class C End Class End Namespace Namespace K Namespace C Class D End Class End Namespace End Namespace Class A Inherits C End Class </file> </compilation>) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) Assert.Same(compilation.GetTypeByMetadataName("N.C"), compilation.GetTypeByMetadataName("A").BaseType) End Sub <Fact()> Public Sub Bug3015() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3015"> <file name="a.vb"> Imports P Imports R Module Module1 Sub Main() Dim x As Q = New Q() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace R Class Q End Class End Namespace Namespace P.Q End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ R.Q ]]>) End Sub <Fact()> Public Sub Bug3014() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug3014"> <file name="a.vb"> Imports P = System Imports R Module C Sub Main() Dim x As P(Of Integer) x=Nothing End Sub End Module Namespace R Class P(Of T) End Class End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC32045: 'System' has no type parameters and so cannot have type arguments. Dim x As P(Of Integer) ~~~~~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AmbiguityInImports() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguityInImports1"> <file name="a.vb"> Namespace NS1 Friend Class CT1 End Class Friend Class CT2 End Class Public Class CT3(Of T) End Class Public Class CT4 End Class Public Module M1 Friend Class CT1 End Class Public Class CT2(Of T) End Class Public Class CT3 End Class End Module Public Module M2 Public Class CT3 End Class End Module End Namespace Namespace NS2 Public Class CT5 End Class Public Module M3 Public Class CT5 End Class End Module End Namespace Namespace NS3 Public Class CT5 End Class End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="AmbiguityInImports3"> <file name="a.vb"> Namespace NS1 Namespace CT4 End Namespace End Namespace Namespace NS2 Namespace CT5 End Namespace End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="AmbiguityInImports2"> <file name="a.vb"> Imports NS2 Imports NS3 Namespace NS1 Module Module1 Sub Test() Dim x1 As CT1 Dim x2 As CT2 Dim x3 As CT3 Dim x4 As CT4 Dim x5 As CT5 x1 = Nothing x2 = Nothing x3 = Nothing x4 = Nothing x5 = Nothing End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation2, <expected> BC30389: 'NS1.CT1' is not accessible in this context because it is 'Friend'. Dim x1 As CT1 ~~~ BC30389: 'NS1.CT2' is not accessible in this context because it is 'Friend'. Dim x2 As CT2 ~~~ BC30562: 'CT3' is ambiguous between declarations in Modules 'NS1.M1, NS1.M2'. Dim x3 As CT3 ~~~ BC30560: 'CT4' is ambiguous in the namespace 'NS1'. Dim x4 As CT4 ~~~ BC30560: 'CT5' is ambiguous in the namespace 'NS2'. Dim x5 As CT5 ~~~ </expected>) End Sub <Fact()> Public Sub TieBreakingInImports() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports1"> <file name="a.vb"> Namespace NS1 Namespace Test1 Public Class Test3 End Class End Namespace Public Class Test2 End Class Public Class Test5 End Class End Namespace Namespace NS2 Namespace Test1 Public Class Test4 End Class End Namespace Public Class Test5 End Class End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports2"> <file name="a.vb"> Namespace NS3 Class Test1 End Class Class Test1(Of T) End Class Class Test5 End Class End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="TieBreakingInImports3"> <file name="a.vb"> Namespace NS2 Class Test2(Of T) End Class End Namespace </file> </compilation>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation4, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) Dim compilation5 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS2 Imports NS3 Imports NS1 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation5, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS2, NS1'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) Dim compilation6 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="TieBreakingInImports4"> <file name="a.vb"> Imports NS3 Imports NS1 Imports NS2 Module Test Sub Test() Dim x1 As Test1 = Nothing Dim x2 As Test1(Of Integer) = Nothing Dim x3 As Test2(Of Integer) = Nothing Dim x4 As Test5 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation3)}) CompilationUtils.AssertTheseDiagnostics(compilation6, <expected> BC30182: Type expected. Dim x1 As Test1 = Nothing ~~~~~ BC30389: 'NS3.Test1(Of T)' is not accessible in this context because it is 'Friend'. Dim x2 As Test1(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30389: 'NS2.Test2(Of T)' is not accessible in this context because it is 'Friend'. Dim x3 As Test2(Of Integer) = Nothing ~~~~~~~~~~~~~~~~~ BC30561: 'Test5' is ambiguous, imported from the namespaces or types 'NS1, NS2'. Dim x4 As Test5 = Nothing ~~~~~ </expected>) End Sub <Fact()> Public Sub RecursiveCheckForAccessibleTypesWithinANamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveCheckForAccessibleTypesWithinANamespace1"> <file name="a.vb"> Imports P Module Module1 Sub Main() Dim x As Q.R.S = New Q.R.S() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace P Namespace Q Namespace R Public Class S End Class End Namespace End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ P.Q.R.S ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="RecursiveCheckForAccessibleTypesWithinANamespace2"> <file name="a.vb"> Imports P Module Module1 Sub Main() Dim x As Q.R.S = New Q.R.S() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace P Namespace Q Namespace R Friend Class S End Class Friend Class T End Class End Namespace End Namespace End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ P.Q.R.S ]]>) End Sub <Fact()> Public Sub DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace() ' We need to be careful about metadata references we use here. ' The test checks that fields of namespace symbols are initialized in certain order. ' If we used a shared Mscorlib reference then other tests might have already initialized it's shared AssemblySymbol. Dim nonSharedMscorlibReference = AssemblyMetadata.CreateFromImage(ResourcesNet451.mscorlib).GetReference(display:="mscorlib.v4_0_30319.dll") Dim c = VisualBasicCompilation.Create("DoNotLoadTypesForAccessibilityOfMostAccessibleTypeWithinANamespace", syntaxTrees:={Parse(<text> Namespace P End Namespace </text>.Value)}, references:={nonSharedMscorlibReference}) Dim system = c.Assembly.Modules(0).GetReferencedAssemblySymbols()(0).GlobalNamespace.GetMembers("System").OfType(Of PENamespaceSymbol)().Single() Dim deployment = system.GetMembers("Deployment").OfType(Of PENamespaceSymbol)().Single() Dim internal = deployment.GetMembers("Internal").OfType(Of PENamespaceSymbol)().Single() Dim isolation = internal.GetMembers("Isolation").OfType(Of PENamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolation.AreTypesLoaded) Assert.Equal(Accessibility.Friend, isolation.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolation.AreTypesLoaded) Assert.Equal(Accessibility.Friend, isolation.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, deployment.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, internal.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) isolation.GetTypeMembers() Assert.True(isolation.AreTypesLoaded) Dim io = system.GetMembers("IO").OfType(Of PENamespaceSymbol)().Single() Dim isolatedStorage = io.GetMembers("IsolatedStorage").OfType(Of PENamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolatedStorage.AreTypesLoaded) Assert.Equal(Accessibility.Public, isolatedStorage.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.False(isolatedStorage.AreTypesLoaded) Assert.Equal(Accessibility.Public, isolatedStorage.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, system.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, io.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) End Sub <Fact()> Public Sub TestMergedNamespaceContainsTypesAccessibleFrom() Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C1"> <file name="a.vb"> Namespace P Namespace Q Public Class R End Class End Namespace End Namespace </file> </compilation>) Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C2"> <file name="a.vb"> Namespace P Namespace Q Friend Class S End Class End Namespace End Namespace </file> </compilation>) Dim c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C3"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c1), New VisualBasicCompilationReference(c2)}) Dim p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() Dim q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) Assert.Equal(Accessibility.Public, q.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Public, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(0, p.RawContainsAccessibleTypes) Assert.Equal(0, q.RawContainsAccessibleTypes) c3 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C3"> <file name="a.vb"> Namespace P Namespace Q Friend Class U End Class End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c2)}) p = c3.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.True(q.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.True, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.True, q.RawContainsAccessibleTypes) Assert.True(p.ContainsTypesAccessibleFrom(c3.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Dim c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C4"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)}) p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes) Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes) c4 = CompilationUtils.CreateCompilationWithMscorlib40AndReferences( <compilation name="C4"> <file name="a.vb"> Namespace P Namespace Q End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(c3), New VisualBasicCompilationReference(c2)}) p = c4.GlobalNamespace.GetMembers("P").OfType(Of MergedNamespaceSymbol)().Single() q = p.GetMembers("Q").OfType(Of MergedNamespaceSymbol)().Single() Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.Equal(Accessibility.Friend, q.DeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Private, p.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(Accessibility.Friend, q.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.Unknown, q.RawContainsAccessibleTypes) Assert.False(q.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(ThreeState.Unknown, p.RawContainsAccessibleTypes) Assert.Equal(ThreeState.False, q.RawContainsAccessibleTypes) Assert.False(p.ContainsTypesAccessibleFrom(c4.Assembly)) Assert.Equal(ThreeState.False, p.RawContainsAccessibleTypes) End Sub <Fact()> Public Sub Bug4128() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4128"> <file name="a.vb"> Imports A = C.B Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 Imports XXXXYYY = UNKNOWN(Of UNKNOWN) Module X Class C End Class End Module Module Y Class C End Class End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30562: 'C' is ambiguous between declarations in Modules 'X, Y'. Imports A = C.B ~ BC40056: Namespace or type specified in the Imports 'UNKNOWN.UNKNOWN' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30002: Type 'UNKNOWN' is not defined. Imports XXXXXXX = UNKNOWN.UNKNOWN(Of UNKNOWN) 'BUG #4115 ~~~~~~~ BC40056: Namespace or type specified in the Imports 'UNKNOWN' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports XXXXYYY = UNKNOWN(Of UNKNOWN) ~~~~~~~~~~~~~~~~~~~ BC30002: Type 'UNKNOWN' is not defined. Imports XXXXYYY = UNKNOWN(Of UNKNOWN) ~~~~~~~ </expected>) End Sub <Fact()> Public Sub Bug4220() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4220"> <file name="a.vb"> Imports A Imports A.B Imports A.B Namespace A Module B End Module End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31051: Namespace or type 'B' has already been imported. Imports A.B ~~~ </expected>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4220"> <file name="a.vb"> Imports A Imports A.B Module Module1 Sub Main() c() End Sub End Module Namespace A Module B Public Sub c() System.Console.WriteLine("Sub c()") End Sub End Module End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ Sub c() ]]>) End Sub <Fact()> Public Sub Bug4180() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="Bug4180"> <file name="a.vb"> Namespace System Class [Object] End Class Class C Inherits [Object] End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> </expected>) Assert.Same(compilation.Assembly.GetTypeByMetadataName("System.Object"), compilation.GetTypeByMetadataName("System.C").BaseType) Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C1"> <file name="a.vb"> Namespace NS1 Namespace NS2 Public Class C1 End Class End Namespace End Namespace Namespace NS5 Public Module Module3 Public Sub Test() End Sub End Module End Namespace </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="C2"> <file name="a.vb"> Namespace NS1 Namespace NS2 Namespace C1 Public Class C2 End Class End Namespace End Namespace End Namespace Namespace NS5 Public Module Module4 Public Sub Test() End Sub End Module End Namespace </file> </compilation>) Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS1 Module Module1 Sub Main() Dim x As NS2.C1.C2 = New NS2.C1.C2() System.Console.WriteLine(x.GetType()) End Sub End Module Namespace NS2 Namespace C1 End Namespace End Namespace End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation3, <![CDATA[ NS1.NS2.C1.C2 ]]>) Dim compilation4 = CompilationUtils.CreateCompilationWithMscorlib40( <compilation name="C4"> <file name="a.vb"> Namespace NS1 Namespace NS2 Namespace C1 Public Class C3 End Class End Namespace End Namespace End Namespace </file> </compilation>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Imports NS1 Module Module1 Sub Main() Dim x As NS2.C1.C2 = Nothing End Sub End Module </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2), New VisualBasicCompilationReference(compilation4)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation3, <expected> BC30560: 'C1' is ambiguous in the namespace 'NS1.NS2'. Dim x As NS2.C1.C2 = Nothing ~~~~~~ </expected>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS5 Module Module1 Sub Main() Test() End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation3, <expected> BC30562: 'Test' is ambiguous between declarations in Modules 'NS5.Module3, NS5.Module4'. Test() ~~~~ </expected>) compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation name="C3"> <file name="a.vb"> Namespace NS5 Module Module1 Sub Main() Test() End Sub End Module Module Module2 Sub Test() System.Console.WriteLine("Module2.Test") End Sub End Module End Namespace </file> </compilation>, {New VisualBasicCompilationReference(compilation1), New VisualBasicCompilationReference(compilation2)}, TestOptions.ReleaseExe) CompileAndVerify(compilation3, <![CDATA[ Module2.Test ]]>) End Sub <Fact()> Public Sub Bug4817() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports A Imports B Class A Shared Sub Goo() System.Console.WriteLine("A.Goo()") End Sub End Class Class B Inherits A End Class Module C Sub Main() Goo() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ A.Goo() ]]>) compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports A Imports B Class A Shared Sub Goo() System.Console.WriteLine("A.Goo()") End Sub End Class Class B Inherits A Overloads Shared Sub Goo(x As Integer) System.Console.WriteLine("B.Goo()") End Sub End Class Module C Sub Main() Goo() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30561: 'Goo' is ambiguous, imported from the namespaces or types 'A, B, A'. Goo() ~~~ </expected>) End Sub <Fact()> Public Sub LookupOptionMustBeInstance() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Option Explicit On Interface I Sub GooInstance() End Interface Class A Public Shared Sub GooShared() End Sub Public Sub GooInstance() End Sub End Class Module Module1 Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) Dim context = GetContext(compilation, "a.vb", "Sub Main") Dim globalNS = compilation.GlobalNamespace Dim classA = DirectCast(globalNS.GetMembers("A").Single(), NamedTypeSymbol) Dim gooShared = DirectCast(classA.GetMembers("GooShared").Single(), MethodSymbol) Dim gooInstance = DirectCast(classA.GetMembers("GooInstance").Single(), MethodSymbol) Dim lr As LookupResult ' Find Shared member lr = New LookupResult() context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustNotBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(gooShared, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) lr = New LookupResult() context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustNotBeInstance, Nothing) Assert.Equal(LookupResultKind.MustNotBeInstance, lr.Kind) Assert.True(lr.HasDiagnostic) 'error BC30469: Reference to a non-shared member requires an object reference. lr = New LookupResult() context.LookupMember(lr, classA, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(gooInstance, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) lr = New LookupResult() context.LookupMember(lr, classA, "GooShared", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(LookupResultKind.MustBeInstance, lr.Kind) Assert.False(lr.HasDiagnostic) Dim interfaceI = DirectCast(globalNS.GetMembers("I").Single(), NamedTypeSymbol) Dim ifooInstance = DirectCast(interfaceI.GetMembers("GooInstance").Single(), MethodSymbol) lr = New LookupResult() context.LookupMember(lr, interfaceI, "GooInstance", 0, LookupOptions.MustBeInstance, Nothing) Assert.Equal(1, lr.Symbols.Count) Assert.Equal(ifooInstance, lr.Symbols.Single()) Assert.False(lr.HasDiagnostic) CompilationUtils.AssertNoDeclarationDiagnostics(compilation) End Sub <Fact> <WorkItem(545575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545575")> Public Sub Bug14079() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Interface I Class Goo Shared Sub Boo() End Sub End Class End Interface Class D Sub Goo() End Sub Interface I2 Inherits I Shadows Class Goo(Of T) End Class Class C Sub Bar() Goo.Boo() End Sub End Class End Interface End Class </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) End Sub <Fact(), WorkItem(531293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531293")> Public Sub Bug17900() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug4817"> <file name="a.vb"> Imports Undefined Module Program Event E Sub Main() End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40056: Namespace or type specified in the Imports 'Undefined' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. Imports Undefined ~~~~~~~~~ </expected>) End Sub <Fact()> Public Sub AmbiguousNamespaces_01() Dim compilation = CompilationUtils.CreateEmptyCompilation( <compilation> <file name="a.vb"> Imports System Imports System.Windows.Forms Module Module1 Sub Main() Dim x As ComponentModel.INotifyPropertyChanged = Nothing 'BIND1:"ComponentModel" End Sub End Module </file> </compilation>, references:={Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic, Net451.SystemWindowsForms}) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info = semanticModel.GetSymbolInfo(node) Dim ns = DirectCast(info.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns.NamespaceKind) Assert.Equal("System.ComponentModel", ns.ToTestDisplayString()) Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"}, semanticModel.LookupNamespacesAndTypes(node.Position, name:="ComponentModel").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"System.ComponentModel", "System.Windows.Forms.ComponentModel"}, semanticModel.LookupSymbols(node.Position, name:="ComponentModel").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_02() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Imports System Imports Windows.Foundation Module Module1 Sub Main() Diagnostics.Debug.WriteLine("") 'BIND1:"Diagnostics" Dim x = Diagnostics Diagnostics End Sub End Module </file> </compilation>, WinRtRefs) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30112: 'Diagnostics' is a namespace and cannot be used as an expression. Dim x = Diagnostics ~~~~~~~~~~~ BC30112: 'Diagnostics' is a namespace and cannot be used as an expression. Diagnostics ~~~~~~~~~~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info = semanticModel.GetSymbolInfo(node) Dim ns = DirectCast(info.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Compilation, ns.NamespaceKind) Assert.Equal("System.Diagnostics", ns.ToTestDisplayString()) Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"}, semanticModel.LookupNamespacesAndTypes(node.Position, name:="Diagnostics").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"System.Diagnostics", "Windows.Foundation.Diagnostics"}, semanticModel.LookupSymbols(node.Position, name:="Diagnostics").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_03() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Module Module1 Sub Main() NS3. 'BIND1:"NS3" NS4.T1.M1() 'BIND2:"NS4" End Sub End Module Namespace NS1 Namespace NS3 Namespace NS4 Class T1 Shared Sub M1() End Sub End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS3 Namespace NS4 Class T2 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Dim ns2 = DirectCast(info2.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns2.NamespaceKind) Assert.Equal("NS1.NS3.NS4", ns2.ToTestDisplayString()) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Dim ns1 = DirectCast(info1.Symbol, NamespaceSymbol) Assert.Equal(NamespaceKind.Module, ns1.NamespaceKind) Assert.Equal("NS1.NS3", ns1.ToTestDisplayString()) Assert.Equal({"NS1.NS3", "NS2.NS3"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS3").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS3", "NS2.NS3"}, semanticModel.LookupSymbols(node1.Position, name:="NS3").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_04() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS4 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = GetType(NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1) 'BIND3:"T1" End Sub Class Test1 Inherits NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" End Class Sub Main2() Dim x = NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1. 'BIND9:"T1" M1() End Sub Sub Main3() Dim x = GetType(NS6) 'BIND10:"NS6" Dim y = GetType(NS6. 'BIND11:"NS6" NS7) 'BIND12:"NS7" End Sub Class Test2 Inherits NS6 'BIND13:"NS6" End Class Class Test3 Inherits NS6. 'BIND14:"NS6" NS7 'BIND15:"NS7" End Class Sub Main4() NS6 'BIND16:"NS6" NS6. 'BIND17:"NS6" NS7 'BIND18:"NS7" End Sub <NS6> 'BIND19:"NS6" <NS6. 'BIND20:"NS6" NS7> 'BIND21:"NS7" <NS6. 'BIND22:"NS6" NS7. 'BIND23:"NS7" T1> 'BIND24:"T1" Class Test4 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS4 Namespace NS6 Namespace NS7 Namespace T1 Class T2 End Class End Namespace End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Dim x = GetType(NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Inherits NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. Dim x = NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30182: Type expected. Dim x = GetType(NS6) 'BIND10:"NS6" ~~~ BC30182: Type expected. Dim y = GetType(NS6. 'BIND11:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. Inherits NS6 'BIND13:"NS6" ~~~ BC30182: Type expected. Inherits NS6. 'BIND14:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30112: 'NS6' is a namespace and cannot be used as an expression. NS6 'BIND16:"NS6" ~~~ BC30112: 'NS6.NS7' is a namespace and cannot be used as an expression. NS6. 'BIND17:"NS6" ~~~~~~~~~~~~~~~~~~~ BC30182: Type expected. <NS6> 'BIND19:"NS6" ~~~ BC30182: Type expected. <NS6. 'BIND20:"NS6" ~~~~~~~~~~~~~~~~~~~ BC37229: 'T1' is ambiguous between declarations in namespaces 'NS1.NS6.NS7, NS2.NS6.NS7, NS4.NS6.NS7, NS5.NS6.NS7'. <NS6. 'BIND22:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(24) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 24} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7.T1", "NS2.NS6.NS7.T1", "NS4.NS6.NS7.T1", "NS5.NS6.NS7.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 23} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 22} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {10, 13, 16, 19} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(If(i = 16, CandidateReason.Ambiguous, If(i = 19, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info2.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {12, 15, 18, 21} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(If(i = 18, CandidateReason.Ambiguous, If(i = 21, CandidateReason.NotAnAttributeType, CandidateReason.NotATypeOrNamespace)), info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS4.NS6.NS7", "NS5.NS6.NS7", "NS9.NS6.NS7"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {11, 14, 17, 20} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_05() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS4 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = GetType(NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1) 'BIND3:"T1" End Sub Class Test1 Inherits NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" End Class Sub Main2() NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1. 'BIND9:"T1" M1() End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Class T1 Inherits System.Attribute Shared Sub M1() End Sub End Class End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Class T2 End Class End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Class T1 End Class End Namespace End Namespace End Namespace Namespace NS4 Namespace NS6 Namespace NS7 Namespace T4 Class T2 End Class End Namespace End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7.T1", info3.Symbol.ToTestDisplayString()) Next Dim info12 = semanticModel.GetSymbolInfo(nodes(12)) Assert.Equal("Sub NS1.NS6.NS7.T1..ctor()", info12.Symbol.ToTestDisplayString()) For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS4.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_06() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" Dim y = GetType(NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" M1) 'BIND6:"M1" End Sub <NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" M1> 'BIND9:"M1" Class Test1 Inherits NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" M1 'BIND12:"M1" End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30562: 'M1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.T1, NS2.NS6.NS7.T1, NS5.NS6.NS7.T1'. Dim x = NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. Dim y = GetType(NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. <NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30002: Type 'NS6.NS7.M1' is not defined. Inherits NS6. 'BIND10:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 12} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(If(i = 3, CandidateReason.Ambiguous, CandidateReason.NotATypeOrNamespace), info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"Sub NS1.NS6.NS7.T1.M1()", "Sub NS2.NS6.NS7.T1.M1()", "Sub NS5.NS6.NS7.T1.M1()"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_07() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() Dim x = NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" End Sub End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1(x as Integer) End Sub Sub M1(x as Long) End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30516: Overload resolution failed because no accessible 'M1' accepts this number of arguments. M1() 'BIND3:"M1" ~~ </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim info3 = semanticModel.GetSymbolInfo(node3) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.OverloadResolutionFailure, info3.CandidateReason) Assert.Equal({"Sub NS1.NS6.NS7.T1.M1(x As System.Int32)", "Sub NS1.NS6.NS7.T1.M1(x As System.Int64)"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_08() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Sub Main() NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" M1() 'BIND3:"M1" End Sub End Module Namespace NS1 Namespace NS6 Namespace NS7 Module T1 Sub M1() End Sub End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module T1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace </file> </compilation>) CompilationUtils.AssertNoDiagnostics(compilation) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim node3 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 3) Dim info3 = semanticModel.GetSymbolInfo(node3) Assert.Equal("Sub NS1.NS6.NS7.T1.M1()", info3.Symbol.ToTestDisplayString()) Dim node2 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 2) Dim info2 = semanticModel.GetSymbolInfo(node2) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Dim node1 As IdentifierNameSyntax = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", 1) Dim info1 = semanticModel.GetSymbolInfo(node1) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(node1.Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) End Sub <Fact()> Public Sub AmbiguousNamespaces_09() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Class Test1 Inherits NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1 'BIND3:"T1" End Class Sub Main() NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" Dim x = GetType(NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1) 'BIND9:"T1" End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module Module1 Class T1 End Class End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. Inherits NS6. 'BIND1:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. Dim x = GetType(NS6. 'BIND7:"NS6" ~~~~~~~~~~~~~~~~~~ BC30562: 'T1' is ambiguous between declarations in Modules 'NS1.NS6.NS7.Module1, NS2.NS6.NS7.Module1, NS5.NS6.NS7.Module1'. <NS6. 'BIND10:"NS6" ~~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9, 12} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info3.Symbol) Assert.Equal(CandidateReason.Ambiguous, info3.CandidateReason) ' Content of this list should determine content of lists below !!! Assert.Equal({"NS1.NS6.NS7.Module1.T1", "NS2.NS6.NS7.Module1.T1", "NS5.NS6.NS7.Module1.T1"}, info3.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info2.Symbol) Assert.Equal(CandidateReason.Ambiguous, info2.CandidateReason) Assert.Equal({"NS1.NS6.NS7", "NS2.NS6.NS7", "NS5.NS6.NS7"}, info2.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Null(info1.Symbol) Assert.Equal(CandidateReason.Ambiguous, info1.CandidateReason) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS5.NS6"}, info1.CandidateSymbols.AsEnumerable().Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> Public Sub AmbiguousNamespaces_10() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports NS1 Imports NS2 Imports NS3 Imports NS5 Imports NS9 Module Module1 Class Test1 Inherits NS6. 'BIND1:"NS6" NS7. 'BIND2:"NS7" T1 'BIND3:"T1" End Class Sub Main() NS6. 'BIND4:"NS6" NS7. 'BIND5:"NS7" T1 'BIND6:"T1" Dim x = GetType(NS6. 'BIND7:"NS6" NS7. 'BIND8:"NS7" T1) 'BIND9:"T1" End Sub <NS6. 'BIND10:"NS6" NS7. 'BIND11:"NS7" T1> 'BIND12:"T1" Class Test2 End Class End Module Namespace NS1 Namespace NS6 Namespace NS7 Module Module1 Class T1 Inherits System.Attribute End Class End Module End Namespace End Namespace End Namespace Namespace NS2 Namespace NS6 Namespace NS7 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS3 Namespace NS6 Namespace NS8 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS5 Namespace NS6 Namespace NS7 Module Module1 End Module End Namespace End Namespace End Namespace Namespace NS9 Namespace NS6 Namespace NS7 Class T3 End Class End Namespace End Namespace End Namespace ]]></file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC30109: 'Module1.T1' is a class type and cannot be used as an expression. NS6. 'BIND4:"NS6" ~~~~~~~~~~~~~~~~~~ ]]></expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = DirectCast(compilation.GetSemanticModel(tree), VBSemanticModel) Dim nodes(12) As IdentifierNameSyntax For i As Integer = 1 To nodes.Length - 1 nodes(i) = CompilationUtils.FindBindingText(Of IdentifierNameSyntax)(compilation, "a.vb", i) Next For Each i In {3, 6, 9} Dim info3 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7.Module1.T1", info3.Symbol.ToTestDisplayString()) Next Dim info12 = semanticModel.GetSymbolInfo(nodes(12)) Assert.Equal("Sub NS1.NS6.NS7.Module1.T1..ctor()", info12.Symbol.ToTestDisplayString()) For Each i In {2, 5, 8, 11} Dim info2 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6.NS7", info2.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info2.Symbol, NamespaceSymbol).NamespaceKind) Next For Each i In {1, 4, 7, 10} Dim info1 = semanticModel.GetSymbolInfo(nodes(i)) Assert.Equal("NS1.NS6", info1.Symbol.ToTestDisplayString()) Assert.Equal(NamespaceKind.Module, DirectCast(info1.Symbol, NamespaceSymbol).NamespaceKind) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupNamespacesAndTypes(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Assert.Equal({"NS1.NS6", "NS2.NS6", "NS3.NS6", "NS5.NS6", "NS9.NS6"}, semanticModel.LookupSymbols(nodes(i).Position, name:="NS6").AsEnumerable(). Select(Function(s) s.ToTestDisplayString()).OrderBy(Function(s) s).ToArray()) Next End Sub <Fact()> <WorkItem(842056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842056")> Public Sub AmbiguousNamespaces_11() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports A Imports B Namespace A.X Class C End Class End Namespace Namespace B.X Class C End Class End Namespace Module M Dim c As X.C End Module ]]></file> </compilation>, TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(compilation, <expected><![CDATA[ BC37229: 'C' is ambiguous between declarations in namespaces 'A.X, B.X'. Dim c As X.C ~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants01() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants01b() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, DATETIME = DateTime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.Datetime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) vbCompilation.VerifyDiagnostics() ' no obsolete diagnostic - we select the first one of the given name CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02b() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime, DATETIME, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02c() Dim csCompilation = CreateCSharpCompilation("CSEnum", <![CDATA[ public enum Color { Red, Green, DateTime, [System.Obsolete] Datetime = DateTime, [System.Obsolete] DATETIME, Blue, } ]]>, compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) csCompilation.VerifyDiagnostics() Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedCompilations:={csCompilation}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02d() Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum", <![CDATA[ Public Enum Color Red Green DateTime <System.Obsolete> Datetime = DateTime DATETIME Blue End Enum ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(vbCompilation1, <expected><![CDATA[ BC31421: 'Datetime' is already declared in this enum. <System.Obsolete> Datetime = DateTime ~~~~~~~~ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. <System.Obsolete> Datetime = DateTime ~~~~~~~~ BC31421: 'DATETIME' is already declared in this enum. DATETIME ~~~~~~~~ ]]></expected>) Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ BC31429: 'DateTime' is ambiguous because multiple kinds of members with this name exist in enum 'Color'. System.Console.WriteLine(CInt(Color.DateTime)) ~~~~~~~~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(2909, "https://github.com/dotnet/roslyn/issues/2909")> Public Sub AmbiguousEnumConstants02e() Dim vbCompilation1 = CreateVisualBasicCompilation("VBEnum", <![CDATA[ Public Enum Color Red Green DateTime <System.Obsolete> Datetime = 2 Blue End Enum ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(vbCompilation1, <expected><![CDATA[ BC31421: 'Datetime' is already declared in this enum. <System.Obsolete> Datetime = 2 ~~~~~~~~ ]]></expected>) Dim vbCompilation = CreateVisualBasicCompilation("VBEnumClient", <![CDATA[ Public Module Program Sub Main() System.Console.WriteLine(CInt(Color.DateTime)) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication), referencedAssemblies:={New VisualBasicCompilationReference(vbCompilation1), MscorlibRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(vbCompilation, <expected><![CDATA[ ]]></expected>) CompileAndVerify(vbCompilation, expectedOutput:="2") End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/SimplifyThisOrMe/SimplifyThisOrMeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyThisOrMe { public partial class SimplifyThisOrMeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyThisOrMeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyThisOrMeDiagnosticAnalyzer(), new CSharpSimplifyThisOrMeCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { private int x = 0; public void z() { var a = [|this.x|]; } }", @" using System; class C { private int x = 0; public void z() { var a = x; } }"); } [WorkItem(6682, "https://github.com/dotnet/roslyn/issues/6682")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestThisWithNoType() { await TestInRegularAndScriptAsync( @"class Program { dynamic x = 7; static void Main(string[] args) { [|this|].x = default(dynamic); } }", @"class Program { dynamic x = 7; static void Main(string[] args) { x = default(dynamic); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestAppropriateDiagnosticOnMissingQualifier() { await TestDiagnosticInfoAsync( @"class C { int SomeProperty { get; set; } void M() { [|this|].SomeProperty = 1; } }", options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveThis() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = {|FixAllInSolution:this.x|}; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveMemberAccessQualification() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { {|FixAllInSolution:this.Property|} = 1; var x = this.OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { this.StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { Property = 1; var x = OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var options = new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, }; await TestInRegularAndScriptAsync( initialMarkup: input, expectedMarkup: expected, options: options); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.SimplifyThisOrMe; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SimplifyThisOrMe { public partial class SimplifyThisOrMeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public SimplifyThisOrMeTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpSimplifyThisOrMeDiagnosticAnalyzer(), new CSharpSimplifyThisOrMeCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestSimplifyDiagnosticId() { await TestInRegularAndScriptAsync( @" using System; class C { private int x = 0; public void z() { var a = [|this.x|]; } }", @" using System; class C { private int x = 0; public void z() { var a = x; } }"); } [WorkItem(6682, "https://github.com/dotnet/roslyn/issues/6682")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestThisWithNoType() { await TestInRegularAndScriptAsync( @"class Program { dynamic x = 7; static void Main(string[] args) { [|this|].x = default(dynamic); } }", @"class Program { dynamic x = 7; static void Main(string[] args) { x = default(dynamic); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] public async Task TestAppropriateDiagnosticOnMissingQualifier() { await TestDiagnosticInfoAsync( @"class C { int SomeProperty { get; set; } void M() { [|this|].SomeProperty = 1; } }", options: Option(CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Warning), diagnosticId: IDEDiagnosticIds.RemoveQualificationDiagnosticId, diagnosticSeverity: DiagnosticSeverity.Warning); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveThis() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = {|FixAllInSolution:this.x|}; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x2; System.Int16 s1 = this.y2; System.Int32 i2 = this.z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB2 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x; System.Int16 s1 = y; System.Int32 i2 = z; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } class ProgramB3 { private int x2 = 0; private int y2 = 0; private int z2 = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = x2; System.Int16 s1 = y2; System.Int32 i2 = z2; System.Console.Write(i1 + s1 + i2); System.Console.WriteLine(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyThisOrMe)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveMemberAccessQualification() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { {|FixAllInSolution:this.Property|} = 1; var x = this.OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { this.StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class C { int Property { get; set; } int OtherProperty { get; set; } void M() { Property = 1; var x = OtherProperty; } } </Document> <Document> using System; class D { string StringProperty { get; set; } int field; void N() { StringProperty = string.Empty; this.field = 0; // ensure qualification isn't removed } } </Document> </Project> </Workspace>"; var options = new OptionsCollection(GetLanguage()) { { CodeStyleOptions2.QualifyPropertyAccess, false, NotificationOption2.Suggestion }, { CodeStyleOptions2.QualifyFieldAccess, true, NotificationOption2.Suggestion }, }; await TestInRegularAndScriptAsync( initialMarkup: input, expectedMarkup: expected, options: options); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/EqualsKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EqualsKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y join a in e on o1 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterEquals() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn1() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn2() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn3() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in y on $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EqualsKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from x in y join a in e on o1 $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterEquals() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in o1 equals $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn1() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn2() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterJoinLeftExpr_NotAfterIn3() { await VerifyAbsenceAsync(AddInsideMethod( @"var q = from x in y join a.b c in y on $$")); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ITypeOfExpression.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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(Integer)'BIND:"GetType(Integer)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)') TypeOperand: System.Int32 ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_NonPrimitiveTypeArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(C)'BIND:"GetType(C)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(C)') TypeOperand: C ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_ErrorTypeArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(UndefinedType)'BIND:"GetType(UndefinedType)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(UndefinedType)') TypeOperand: UndefinedType ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'UndefinedType' is not defined. t = GetType(UndefinedType)'BIND:"GetType(UndefinedType)" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_IdentifierArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(t)'BIND:"GetType(t)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(t)') TypeOperand: t ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 't' is not defined. t = GetType(t)'BIND:"GetType(t)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_ExpressionArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(M2())'BIND:"GetType(M2())" End Sub Function M2() As Type Return Nothing End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(M2())') TypeOperand: M2() ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'M2' is not defined. t = GetType(M2())'BIND:"GetType(M2())" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_MissingArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType()'BIND:"GetType()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType()') TypeOperand: ? ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. t = GetType()'BIND:"GetType()" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub TypeOfFlow_01() Dim source = <![CDATA[ Imports System Class C Public Sub M(t As Type)'BIND:"Public Sub M(t As Type)" t = GetType(Boolean) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 't = GetType(Boolean)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type, IsImplicit) (Syntax: 't = GetType(Boolean)') Left: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't') Right: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Boolean)') TypeOperand: System.Boolean Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub IsTypeFlow_01() Dim source = <![CDATA[ Class C Sub M(c As C2, b As Boolean)'BIND:"Sub M(c As C2, b As Boolean)" b = TypeOf c Is C2 End Sub Class C2 : Dim i As Integer : End Class End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = TypeOf c Is C2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'b = TypeOf c Is C2') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'TypeOf c Is C2') Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'c') IsType: C.C2 Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub IsTypeFlow_02() Dim source = <![CDATA[ Class C Sub M(x As C2, y As C2, b As Boolean)'BIND:"Sub M(x As C2, y As C2, b As Boolean)" b = TypeOf If(x, y) IsNot C2 End Sub Class C2 : Dim i As Integer : End Class End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'x') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'x') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'y') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = TypeOf ... y) IsNot C2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'b = TypeOf ... y) IsNot C2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsTypeOperation (IsNotExpression) (OperationKind.IsType, Type: System.Boolean) (Syntax: 'TypeOf If(x, y) IsNot C2') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'If(x, y)') IsType: C.C2 Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) 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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(Integer)'BIND:"GetType(Integer)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Integer)') TypeOperand: System.Int32 ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_NonPrimitiveTypeArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(C)'BIND:"GetType(C)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(C)') TypeOperand: C ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_ErrorTypeArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(UndefinedType)'BIND:"GetType(UndefinedType)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(UndefinedType)') TypeOperand: UndefinedType ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'UndefinedType' is not defined. t = GetType(UndefinedType)'BIND:"GetType(UndefinedType)" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_IdentifierArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(t)'BIND:"GetType(t)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(t)') TypeOperand: t ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 't' is not defined. t = GetType(t)'BIND:"GetType(t)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_ExpressionArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType(M2())'BIND:"GetType(M2())" End Sub Function M2() As Type Return Nothing End Function End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType(M2())') TypeOperand: M2() ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30002: Type 'M2' is not defined. t = GetType(M2())'BIND:"GetType(M2())" ~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub TestGetType_MissingArgument() Dim source = <![CDATA[ Imports System Class C Sub M(t As Type) t = GetType()'BIND:"GetType()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ ITypeOfOperation (OperationKind.TypeOf, Type: System.Type, IsInvalid) (Syntax: 'GetType()') TypeOperand: ? ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30182: Type expected. t = GetType()'BIND:"GetType()" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of GetTypeExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub TypeOfFlow_01() Dim source = <![CDATA[ Imports System Class C Public Sub M(t As Type)'BIND:"Public Sub M(t As Type)" t = GetType(Boolean) End Sub End Class]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 't = GetType(Boolean)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Type, IsImplicit) (Syntax: 't = GetType(Boolean)') Left: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: System.Type) (Syntax: 't') Right: ITypeOfOperation (OperationKind.TypeOf, Type: System.Type) (Syntax: 'GetType(Boolean)') TypeOperand: System.Boolean Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub IsTypeFlow_01() Dim source = <![CDATA[ Class C Sub M(c As C2, b As Boolean)'BIND:"Sub M(c As C2, b As Boolean)" b = TypeOf c Is C2 End Sub Class C2 : Dim i As Integer : End Class End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = TypeOf c Is C2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'b = TypeOf c Is C2') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'TypeOf c Is C2') Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'c') IsType: C.C2 Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub IsTypeFlow_02() Dim source = <![CDATA[ Class C Sub M(x As C2, y As C2, b As Boolean)'BIND:"Sub M(x As C2, y As C2, b As Boolean)" b = TypeOf If(x, y) IsNot C2 End Sub Class C2 : Dim i As Integer : End Class End Class ]]>.Value Dim expectedDiagnostics = String.Empty Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'x') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'x') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: C.C2) (Syntax: 'y') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = TypeOf ... y) IsNot C2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'b = TypeOf ... y) IsNot C2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsTypeOperation (IsNotExpression) (OperationKind.IsType, Type: System.Boolean) (Syntax: 'TypeOf If(x, y) IsNot C2') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C.C2, IsImplicit) (Syntax: 'If(x, y)') IsType: C.C2 Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/Snippets/VisualBasicSnippetCommandHandlerTests.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 Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets <[UseExportProvider]> Public Class VisualBasicSnippetCommandHandlerTests <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionInserted() Dim markup = "Public Class$$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(7, 5), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("Public Class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionNotInsertedCausesInsertedTab() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSessionDoesNotCauseCauseAnotherExpansion() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSession() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryHandleTabCalled) Assert.Equal("Class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInMiddleOfWordCreatesSession() Dim markup = "Cla$$ss" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Cla ss", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInWhiteSpaceDoesNotCreateSession() Dim markup = "Class $$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionDoesNotCreateSession() Dim markup = <Markup><![CDATA[Class SomeClass {|Selection:Sub Goo End Sub$$|} End Class ]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[Class SomeClass End Class ]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionOnWhitespaceQuestionMarkDoesNotCreateSession() Dim markup = <Markup><![CDATA[Class SomeClass {|Selection:Sub Goo End Sub ?$$|} End Class ]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[Class SomeClass End Class ]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_ActiveSession() Dim markup = <Markup><![CDATA[ $$Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_NoActiveSession() Dim markup = <Markup><![CDATA[ $$Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_ActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendReturn() Assert.True(testState.SnippetExpansionClient.TryHandleReturnCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_NoActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendReturn() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_ActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_NoActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Dim expectedText = <Code><![CDATA[ EscapePassedThrough! Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideComment_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() ' If$$ End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideString_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = "What if$$ this fails?" End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideXmlLiteral1_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = <If$$>Testing</If> End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideXmlLiteral2_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = <a>If$$</a> End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabDeletesQuestionMark() Dim markup = <Markup><![CDATA[ Class C ?$$ End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetLineTextFromCaretPosition(), " ") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabNotAfterNullable() Dim markup = <Markup><![CDATA[ Class C Dim x as Integer?$$ End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetLineTextFromCaretPosition(), " Dim x as Integer? ") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabAtBeginningOfFile() Dim markup = <Markup>?$$</Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetDocumentText(), "") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_Tab() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.VisualBasic) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_InsertSnippetCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.VisualBasic) Using testState Dim handler = testState.SnippetCommandHandler Dim state = handler.GetCommandState(New InsertSnippetCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendInsertSnippetCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor.Commanding.Commands Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Snippets <[UseExportProvider]> Public Class VisualBasicSnippetCommandHandlerTests <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionInserted() Dim markup = "Public Class$$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(New Span(7, 5), testState.SnippetExpansionClient.InsertExpansionSpan) Assert.Equal("Public Class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_NoActiveSession_ExpansionNotInsertedCausesInsertedTab() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSessionDoesNotCauseCauseAnotherExpansion() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabAtEndOfWord_ActiveSession() Dim markup = "Class$$" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryHandleTabCalled) Assert.Equal("Class", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInMiddleOfWordCreatesSession() Dim markup = "Cla$$ss" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.True(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Cla ss", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInWhiteSpaceDoesNotCreateSession() Dim markup = "Class $$ Goo" Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("Class Goo", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionDoesNotCreateSession() Dim markup = <Markup><![CDATA[Class SomeClass {|Selection:Sub Goo End Sub$$|} End Class ]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[Class SomeClass End Class ]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabWithSelectionOnWhitespaceQuestionMarkDoesNotCreateSession() Dim markup = <Markup><![CDATA[Class SomeClass {|Selection:Sub Goo End Sub ?$$|} End Class ]]></Markup>.Value Dim expectedResults = <Markup><![CDATA[Class SomeClass End Class ]]></Markup>.Value.Replace(vbLf, vbCrLf) Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(expectedResults, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_ActiveSession() Dim markup = <Markup><![CDATA[ $$Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_BackTab_NoActiveSession() Dim markup = <Markup><![CDATA[ $$Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendBackTab() Assert.True(testState.SnippetExpansionClient.TryHandleBackTabCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_ActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendReturn() Assert.True(testState.SnippetExpansionClient.TryHandleReturnCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Return_NoActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendReturn() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_ActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic, startActiveSession:=True) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Dim expectedText = <Code><![CDATA[ Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_Escape_NoActiveSession() Dim markup = <Markup><![CDATA[ $$ Class Goo End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendEscape() Assert.True(testState.SnippetExpansionClient.TryHandleEscapeCalled) Dim expectedText = <Code><![CDATA[ EscapePassedThrough! Class Goo End Class ]]></Code>.Value.Replace(vbLf, vbCrLf) Assert.Equal(expectedText, testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideComment_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() ' If$$ End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideString_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = "What if$$ this fails?" End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideXmlLiteral1_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = <If$$>Testing</If> End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetCommandHandler_TabInsideXmlLiteral2_NoExpansionInserted() Dim markup = <Markup><![CDATA[ Class C Sub M() Dim x = <a>If$$</a> End Sub End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabDeletesQuestionMark() Dim markup = <Markup><![CDATA[ Class C ?$$ End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetLineTextFromCaretPosition(), " ") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabNotAfterNullable() Dim markup = <Markup><![CDATA[ Class C Dim x as Integer?$$ End Class ]]></Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetLineTextFromCaretPosition(), " Dim x as Integer? ") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets)> Public Sub SnippetListOnQuestionMarkTabAtBeginningOfFile() Dim markup = <Markup>?$$</Markup>.Value Dim testState = SnippetTestState.CreateTestState(markup, LanguageNames.VisualBasic) Using testState testState.SendTab() Assert.Equal(testState.GetDocumentText(), "") Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_Tab() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.VisualBasic) Using testState testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True testState.SendTab() Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for ", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Snippets), Trait(Traits.Feature, Traits.Features.Interactive)> Public Sub SnippetCommandHandler_Interactive_InsertSnippetCommand() Dim markup = "for$$" Dim testState = SnippetTestState.CreateSubmissionTestState(markup, LanguageNames.VisualBasic) Using testState Dim handler = testState.SnippetCommandHandler Dim state = handler.GetCommandState(New InsertSnippetCommandArgs(testState.TextView, testState.SubjectBuffer)) Assert.True(state.IsUnspecified) testState.SnippetExpansionClient.TryInsertExpansionReturnValue = True Assert.False(testState.SendInsertSnippetCommand(AddressOf handler.ExecuteCommand)) Assert.False(testState.SnippetExpansionClient.TryInsertExpansionCalled) Assert.Equal("for", testState.SubjectBuffer.CurrentSnapshot.GetText()) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test2/Rename/DashboardTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class DashboardTests <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNoOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } public void goo(int i) { } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), hasRenameOverload:=True, changedOptionSet:=changingOptions) End Function <WpfTheory> <WorkItem(883263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883263")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithInvalidOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void $$X(int x) { X(); } void X(int x, int y) { } } </Document> </Project> </Workspace>, host:=host, newName:="Bar", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), changedOptionSet:=changingOptions, hasRenameOverload:=True, unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 1), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(853839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853839")> Public Async Function RenameAttributeAlias(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$Evil = AttributeAttribute; [AttributeAttribute] class AttributeAttribute : System.Attribute { } </Document> </Project> </Workspace>), host:=host, newName:="AttributeAttributeAttribute", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameWithOverloadAndInStringsAndComments(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) changingOptions.Add(RenameOptions.RenameInStrings, True) changingOptions.Add(RenameOptions.RenameInComments, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } /// goo public void goo(int i) { // goo var a = "goo"; } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 5), hasRenameOverload:=True, changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInComments(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInComments, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 6), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInStrings(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInStrings, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInCommentsAndStrings(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInComments, True) changingOptions.Add(RenameOptions.RenameInStrings, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 7), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function NonConflictingEditWithMultipleLocations(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$Goo { void Blah() { Goo f = new Goo(); } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3)) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function NonConflictingEditWithSingleLocation(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$UniqueClassName { void Blah() { Goo f = new Goo(); } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithInstanceField(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { int goo; void Blah(int [|$$bar|]) { goo = [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WorkItem(5923, "DevDiv_Projects/Roslyn")> <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithInstanceFieldMoreThanOnce(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { int goo; void Blah(int [|$$bar|]) { goo = goo + [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 2), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithLocal_Unresolvable(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { void Blah(int [|$$bar|]) { int goo; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 1), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function MoreThanOneUnresolvableConflicts(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { void Blah(int [|$$bar|]) { int goo; goo = [|bar|]; goo = [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3), unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 3), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ConflictsAcrossLanguages_Resolvable(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> namespace N { public class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> Imports N Class Bar Sub Blah() Dim f = new {|N.Goo:Goo|}() End Sub End Class </Document> </Project> </Workspace>), host:=host, newName:="Bar", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_files, 4, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromDefinition_DoesNotForceRenameOverloadsOption(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class C { void M$$() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_1_reference_in_1_file), hasRenameOverload:=True, isRenameOverloadsEditable:=True) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromReference_DoesForceRenameOverloadsOption(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class C { void M() { nameof(M$$).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3), hasRenameOverload:=True, isRenameOverloadsEditable:=False) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromDefinition_WithRenameOverloads_Cascading(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class B { public virtual void [|M|](int x) { nameof([|M|]).ToString(); } } class D : B { public void $$[|M|]() { nameof([|M|]).ToString(); } public override void [|M|](int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 5), changedOptionSet:=changingOptions, hasRenameOverload:=True) End Function Friend Shared Async Function VerifyDashboard( test As XElement, newName As String, searchResultText As String, host As RenameTestHost, Optional hasRenameOverload As Boolean = False, Optional isRenameOverloadsEditable As Boolean = True, Optional changedOptionSet As Dictionary(Of OptionKey, Object) = Nothing, Optional resolvableConflictText As String = Nothing, Optional unresolvableConflictText As String = Nothing, Optional severity As DashboardSeverity = DashboardSeverity.None ) As Tasks.Task Using workspace = CreateWorkspaceWithWaiter(test, host) Dim cursorDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(document) Dim token = document.GetSyntaxTreeAsync().Result.GetRoot().FindToken(cursorPosition) Dim renameService = DirectCast(workspace.GetService(Of IInlineRenameService)(), InlineRenameService) ' Create views for all documents to ensure that undo is hooked up properly For Each d In workspace.Documents d.GetTextView() Next Dim optionSet = workspace.Options If changedOptionSet IsNot Nothing Then For Each entry In changedOptionSet optionSet = optionSet.WithChangedOption(entry.Key, entry.Value) Next End If workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim sessionInfo = renameService.StartInlineSession( document, document.GetSyntaxTreeAsync().Result.GetRoot().FindToken(cursorPosition).Span, CancellationToken.None) ' Perform the edit in the buffer Using edit = cursorDocument.GetTextBuffer().CreateEdit() edit.Replace(token.SpanStart, token.Span.Length, newName) edit.Apply() End Using Using dashboard = New Dashboard( New DashboardViewModel(DirectCast(sessionInfo.Session, InlineRenameSession)), editorFormatMapService:=Nothing, textView:=cursorDocument.GetTextView()) Await WaitForRename(workspace) Dim model = DirectCast(dashboard.DataContext, DashboardViewModel) Assert.Equal(searchResultText, model.SearchText) If String.IsNullOrEmpty(resolvableConflictText) Then Assert.False(model.HasResolvableConflicts, "Expected no resolvable conflicts") Assert.Null(model.ResolvableConflictText) Else Assert.True(model.HasResolvableConflicts, "Expected resolvable conflicts") Assert.Equal(resolvableConflictText, model.ResolvableConflictText) End If If String.IsNullOrEmpty(unresolvableConflictText) Then Assert.False(model.HasUnresolvableConflicts, "Expected no unresolvable conflicts") Assert.Null(model.UnresolvableConflictText) Else Assert.True(model.HasUnresolvableConflicts, "Expected unresolvable conflicts") Assert.Equal(unresolvableConflictText, model.UnresolvableConflictText) End If Assert.Equal(hasRenameOverload, model.Session.HasRenameOverloads) Assert.Equal(isRenameOverloadsEditable, model.IsRenameOverloadsEditable) If Not isRenameOverloadsEditable Then Assert.True(model.DefaultRenameOverloadFlag) End If Assert.Equal(severity, model.Severity) End Using sessionInfo.Session.Cancel() End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithReferenceInUnchangeableDocument(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> public class $$A { } </Document> <Document CanApplyChange="false"> class B { void M() { A a; } } </Document> </Project> </Workspace>), host:=host, newName:="C", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, changedOptionSet:=changingOptions) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Implementation.InlineRename Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class DashboardTests <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNoOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } public void goo(int i) { } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), hasRenameOverload:=True, changedOptionSet:=changingOptions) End Function <WpfTheory> <WorkItem(883263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883263")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithInvalidOverload(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void $$X(int x) { X(); } void X(int x, int y) { } } </Document> </Project> </Workspace>, host:=host, newName:="Bar", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), changedOptionSet:=changingOptions, hasRenameOverload:=True, unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 1), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(853839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/853839")> Public Async Function RenameAttributeAlias(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using $$Evil = AttributeAttribute; [AttributeAttribute] class AttributeAttribute : System.Attribute { } </Document> </Project> </Workspace>), host:=host, newName:="AttributeAttributeAttribute", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameWithOverloadAndInStringsAndComments(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) changingOptions.Add(RenameOptions.RenameInStrings, True) changingOptions.Add(RenameOptions.RenameInComments, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void $$goo() { } /// goo public void goo(int i) { // goo var a = "goo"; } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 5), hasRenameOverload:=True, changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInComments(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInComments, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 6), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInStrings(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInStrings, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> Public Async Function RenameInCommentsAndStrings(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameInComments, True) changingOptions.Add(RenameOptions.RenameInStrings, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class $$Program { /// <summary> /// <Program></Program> /// </summary> /// <param name="args"></param> static void Main(string[] args) { // Program /* Program! Program */ var a = "Program"; } } ]]> </Document> </Project> </Workspace>), host:=host, newName:="P", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 7), changedOptionSet:=changingOptions) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function NonConflictingEditWithMultipleLocations(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$Goo { void Blah() { Goo f = new Goo(); } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3)) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function NonConflictingEditWithSingleLocation(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$UniqueClassName { void Blah() { Goo f = new Goo(); } } </Document> </Project> </Workspace>), host:=host, newName:="", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithInstanceField(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { int goo; void Blah(int [|$$bar|]) { goo = [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WorkItem(5923, "DevDiv_Projects/Roslyn")> <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithInstanceFieldMoreThanOnce(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { int goo; void Blah(int [|$$bar|]) { goo = goo + [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 2), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ParameterConflictingWithLocal_Unresolvable(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { void Blah(int [|$$bar|]) { int goo; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 1), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function MoreThanOneUnresolvableConflicts(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> class Goo { void Blah(int [|$$bar|]) { int goo; goo = [|bar|]; goo = [|bar|]; } } </Document> </Project> </Workspace>), host:=host, newName:="goo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3), unresolvableConflictText:=String.Format(EditorFeaturesResources._0_unresolvable_conflict_s, 3), severity:=DashboardSeverity.Error) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function ConflictsAcrossLanguages_Resolvable(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> namespace N { public class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> Imports N Class Bar Sub Blah() Dim f = new {|N.Goo:Goo|}() End Sub End Class </Document> </Project> </Workspace>), host:=host, newName:="Bar", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_files, 4, 2), resolvableConflictText:=String.Format(EditorFeaturesResources._0_conflict_s_will_be_resolved, 1), severity:=DashboardSeverity.Info) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromDefinition_DoesNotForceRenameOverloadsOption(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class C { void M$$() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_1_reference_in_1_file), hasRenameOverload:=True, isRenameOverloadsEditable:=True) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromReference_DoesForceRenameOverloadsOption(host As RenameTestHost) As Task Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class C { void M() { nameof(M$$).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 3), hasRenameOverload:=True, isRenameOverloadsEditable:=False) End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithNameof_FromDefinition_WithRenameOverloads_Cascading(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> class B { public virtual void [|M|](int x) { nameof([|M|]).ToString(); } } class D : B { public void $$[|M|]() { nameof([|M|]).ToString(); } public override void [|M|](int x) { } } </Document> </Project> </Workspace>), host:=host, newName:="Mo", searchResultText:=String.Format(EditorFeaturesResources.Rename_will_update_0_references_in_1_file, 5), changedOptionSet:=changingOptions, hasRenameOverload:=True) End Function Friend Shared Async Function VerifyDashboard( test As XElement, newName As String, searchResultText As String, host As RenameTestHost, Optional hasRenameOverload As Boolean = False, Optional isRenameOverloadsEditable As Boolean = True, Optional changedOptionSet As Dictionary(Of OptionKey, Object) = Nothing, Optional resolvableConflictText As String = Nothing, Optional unresolvableConflictText As String = Nothing, Optional severity As DashboardSeverity = DashboardSeverity.None ) As Tasks.Task Using workspace = CreateWorkspaceWithWaiter(test, host) Dim cursorDocument = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Assert.NotNull(document) Dim token = document.GetSyntaxTreeAsync().Result.GetRoot().FindToken(cursorPosition) Dim renameService = DirectCast(workspace.GetService(Of IInlineRenameService)(), InlineRenameService) ' Create views for all documents to ensure that undo is hooked up properly For Each d In workspace.Documents d.GetTextView() Next Dim optionSet = workspace.Options If changedOptionSet IsNot Nothing Then For Each entry In changedOptionSet optionSet = optionSet.WithChangedOption(entry.Key, entry.Value) Next End If workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim sessionInfo = renameService.StartInlineSession( document, document.GetSyntaxTreeAsync().Result.GetRoot().FindToken(cursorPosition).Span, CancellationToken.None) ' Perform the edit in the buffer Using edit = cursorDocument.GetTextBuffer().CreateEdit() edit.Replace(token.SpanStart, token.Span.Length, newName) edit.Apply() End Using Using dashboard = New Dashboard( New DashboardViewModel(DirectCast(sessionInfo.Session, InlineRenameSession)), editorFormatMapService:=Nothing, textView:=cursorDocument.GetTextView()) Await WaitForRename(workspace) Dim model = DirectCast(dashboard.DataContext, DashboardViewModel) Assert.Equal(searchResultText, model.SearchText) If String.IsNullOrEmpty(resolvableConflictText) Then Assert.False(model.HasResolvableConflicts, "Expected no resolvable conflicts") Assert.Null(model.ResolvableConflictText) Else Assert.True(model.HasResolvableConflicts, "Expected resolvable conflicts") Assert.Equal(resolvableConflictText, model.ResolvableConflictText) End If If String.IsNullOrEmpty(unresolvableConflictText) Then Assert.False(model.HasUnresolvableConflicts, "Expected no unresolvable conflicts") Assert.Null(model.UnresolvableConflictText) Else Assert.True(model.HasUnresolvableConflicts, "Expected unresolvable conflicts") Assert.Equal(unresolvableConflictText, model.UnresolvableConflictText) End If Assert.Equal(hasRenameOverload, model.Session.HasRenameOverloads) Assert.Equal(isRenameOverloadsEditable, model.IsRenameOverloadsEditable) If Not isRenameOverloadsEditable Then Assert.True(model.DefaultRenameOverloadFlag) End If Assert.Equal(severity, model.Severity) End Using sessionInfo.Session.Cancel() End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameWithReferenceInUnchangeableDocument(host As RenameTestHost) As Task Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Await VerifyDashboard( (<Workspace> <Project Language="C#"> <Document> public class $$A { } </Document> <Document CanApplyChange="false"> class B { void M() { A a; } } </Document> </Project> </Workspace>), host:=host, newName:="C", searchResultText:=EditorFeaturesResources.Rename_will_update_1_reference_in_1_file, changedOptionSet:=changingOptions) End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualBasic/Impl/CodeModel/SyntaxExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Friend Module SyntaxExtensions <Extension> Public Function GetExpression(argument As ArgumentSyntax) As ExpressionSyntax Debug.Assert(TypeOf argument Is SimpleArgumentSyntax OrElse TypeOf argument Is OmittedArgumentSyntax) Return argument.GetExpression() End Function <Extension> Public Function GetName(importsClause As ImportsClauseSyntax) As NameSyntax Debug.Assert(TypeOf importsClause Is SimpleImportsClauseSyntax) Return DirectCast(importsClause, SimpleImportsClauseSyntax).Name End Function <Extension> Public Function GetNameText(method As MethodBaseSyntax) As String Select Case method.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(method, MethodStatementSyntax).Identifier.ToString() Case SyntaxKind.SubNewStatement Return DirectCast(method, SubNewStatementSyntax).NewKeyword.ToString() Case SyntaxKind.OperatorStatement Return DirectCast(method, OperatorStatementSyntax).OperatorToken.ToString() Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(method, DeclareStatementSyntax).Identifier.ToString() Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(method, DelegateStatementSyntax).Identifier.ToString() Case SyntaxKind.EventStatement Return DirectCast(method, EventStatementSyntax).Identifier.ToString() Case SyntaxKind.PropertyStatement Return DirectCast(method, PropertyStatementSyntax).Identifier.ToString() Case Else Debug.Fail(String.Format("Unexpected node kind: {0}", method.Kind)) Return String.Empty End Select End Function <Extension> Public Function Type(method As MethodBaseSyntax) As TypeSyntax Dim asClause As AsClauseSyntax Select Case method.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement asClause = DirectCast(method, MethodStatementSyntax).AsClause Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader asClause = DirectCast(method, LambdaHeaderSyntax).AsClause Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement asClause = DirectCast(method, DeclareStatementSyntax).AsClause Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement asClause = DirectCast(method, DelegateStatementSyntax).AsClause Case SyntaxKind.EventStatement asClause = DirectCast(method, EventStatementSyntax).AsClause Case SyntaxKind.OperatorStatement asClause = DirectCast(method, OperatorStatementSyntax).AsClause Case SyntaxKind.PropertyStatement asClause = DirectCast(method, PropertyStatementSyntax).AsClause Case Else Return Nothing End Select Return If(asClause IsNot Nothing, asClause.Type(), Nothing) End Function <Extension> Public Function Type(parameter As ParameterSyntax) As TypeSyntax Return If(parameter.AsClause IsNot Nothing, parameter.AsClause.Type, Nothing) End Function <Extension> Public Function Type(variableDeclarator As VariableDeclaratorSyntax) As TypeSyntax Return If(variableDeclarator.AsClause IsNot Nothing, variableDeclarator.AsClause.Type(), Nothing) End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Friend Module SyntaxExtensions <Extension> Public Function GetExpression(argument As ArgumentSyntax) As ExpressionSyntax Debug.Assert(TypeOf argument Is SimpleArgumentSyntax OrElse TypeOf argument Is OmittedArgumentSyntax) Return argument.GetExpression() End Function <Extension> Public Function GetName(importsClause As ImportsClauseSyntax) As NameSyntax Debug.Assert(TypeOf importsClause Is SimpleImportsClauseSyntax) Return DirectCast(importsClause, SimpleImportsClauseSyntax).Name End Function <Extension> Public Function GetNameText(method As MethodBaseSyntax) As String Select Case method.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return DirectCast(method, MethodStatementSyntax).Identifier.ToString() Case SyntaxKind.SubNewStatement Return DirectCast(method, SubNewStatementSyntax).NewKeyword.ToString() Case SyntaxKind.OperatorStatement Return DirectCast(method, OperatorStatementSyntax).OperatorToken.ToString() Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(method, DeclareStatementSyntax).Identifier.ToString() Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return DirectCast(method, DelegateStatementSyntax).Identifier.ToString() Case SyntaxKind.EventStatement Return DirectCast(method, EventStatementSyntax).Identifier.ToString() Case SyntaxKind.PropertyStatement Return DirectCast(method, PropertyStatementSyntax).Identifier.ToString() Case Else Debug.Fail(String.Format("Unexpected node kind: {0}", method.Kind)) Return String.Empty End Select End Function <Extension> Public Function Type(method As MethodBaseSyntax) As TypeSyntax Dim asClause As AsClauseSyntax Select Case method.Kind Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement asClause = DirectCast(method, MethodStatementSyntax).AsClause Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader asClause = DirectCast(method, LambdaHeaderSyntax).AsClause Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement asClause = DirectCast(method, DeclareStatementSyntax).AsClause Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement asClause = DirectCast(method, DelegateStatementSyntax).AsClause Case SyntaxKind.EventStatement asClause = DirectCast(method, EventStatementSyntax).AsClause Case SyntaxKind.OperatorStatement asClause = DirectCast(method, OperatorStatementSyntax).AsClause Case SyntaxKind.PropertyStatement asClause = DirectCast(method, PropertyStatementSyntax).AsClause Case Else Return Nothing End Select Return If(asClause IsNot Nothing, asClause.Type(), Nothing) End Function <Extension> Public Function Type(parameter As ParameterSyntax) As TypeSyntax Return If(parameter.AsClause IsNot Nothing, parameter.AsClause.Type, Nothing) End Function <Extension> Public Function Type(variableDeclarator As VariableDeclaratorSyntax) As TypeSyntax Return If(variableDeclarator.AsClause IsNot Nothing, variableDeclarator.AsClause.Type(), Nothing) End Function End Module End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/CodeFixes/UseConditionalExpression/AbstractUseConditionalExpressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractFormattingRule GetMultiLineFormattingRule(); #if CODE_STYLE protected abstract ISyntaxFormattingService GetSyntaxFormattingService(); #endif protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation); protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement); protected abstract Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken); protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defer to our callback to actually make the edits for each diagnostic. In turn, it // will return 'true' if it made a multi-line conditional expression. In that case, // we'll need to explicitly format this node so we can get our special multi-line // formatting in VB and C#. var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); foreach (var diagnostic in diagnostics) { await FixOneAsync( document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false); } var changedRoot = nestedEditor.GetChangedRoot(); // Get the language specific rule for formatting this construct and call into the // formatted to explicitly format things. Note: all we will format is the new // conditional expression as that's the only node that has the appropriate // annotation on it. var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() }; var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken); #if CODE_STYLE var formattedRoot = FormatterHelper.Format(changedRoot, GetSyntaxFormattingService(), SpecializedFormattingAnnotation, options, rules, cancellationToken); #else var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, rules, cancellationToken); #endif changedRoot = formattedRoot; editor.ReplaceNode(root, changedRoot); } /// <summary> /// Helper to create a conditional expression out of two original IOperation values /// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate /// annotations and casts to ensure that the conditional expression preserves semantics, but /// is also properly simplified and formatted. /// </summary> protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync( Document document, IConditionalOperation ifOperation, IOperation trueStatement, IOperation falseStatement, IOperation trueValue, IOperation falseValue, bool isRef, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var condition = ifOperation.Condition.Syntax; if (!isRef) { // If we are going to generate "expr ? true : false" then just generate "expr" // instead. if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false)) { return (TExpressionSyntax)condition.WithoutTrivia(); } // If we are going to generate "expr ? false : true" then just generate "!expr" // instead. if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true)) { return (TExpressionSyntax)generator.Negate(generatorInternal, condition, semanticModel, cancellationToken).WithoutTrivia(); } } var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression( condition.WithoutTrivia(), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue))); conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation); var makeMultiLine = await MakeMultiLineAsync( document, condition, trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false); if (makeMultiLine) { conditionalExpression = conditionalExpression.WithAdditionalAnnotations( SpecializedFormattingAnnotation); } return MakeRef(generatorInternal, isRef, conditionalExpression); } private static bool IsBooleanLiteral(IOperation trueValue, bool val) { if (trueValue is ILiteralOperation) { var constant = trueValue.ConstantValue; return constant.HasValue && constant.Value is bool b && b == val; } return false; } private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode) => isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode; /// <summary> /// Checks if we should wrap the conditional expression over multiple lines. /// </summary> private static async Task<bool> MakeMultiLineAsync( Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax, CancellationToken cancellationToken) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) || !sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) || !sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken())) { return true; } #if CODE_STYLE var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength); #endif if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength) { return true; } return false; } private TExpressionSyntax CastValueIfNecessary( SyntaxGenerator generator, IOperation statement, IOperation value) { if (statement is IThrowOperation throwOperation) return ConvertToExpression(throwOperation); var sourceSyntax = value.Syntax.WithoutTrivia(); // If there was an implicit conversion generated by the compiler, then convert that to an // explicit conversion inside the condition. This is needed as there is no type // inference in conditional expressions, so we need to ensure that the same conversions // that were occurring previously still occur after conversion. Note: the simplifier // will remove any of these casts that are unnecessary. if (value is IConversionOperation conversion && conversion.IsImplicit && conversion.Type != null && conversion.Type.TypeKind != TypeKind.Error) { // Note we only add the cast if the source had no type (like the null literal), or a // non-error type itself. We don't want to insert lots of casts in error code. if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error) { return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax); } } return (TExpressionSyntax)sourceSyntax; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using static Microsoft.CodeAnalysis.UseConditionalExpression.UseConditionalExpressionCodeFixHelpers; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal abstract class AbstractUseConditionalExpressionCodeFixProvider< TStatementSyntax, TIfStatementSyntax, TExpressionSyntax, TConditionalExpressionSyntax> : SyntaxEditorBasedCodeFixProvider where TStatementSyntax : SyntaxNode where TIfStatementSyntax : TStatementSyntax where TExpressionSyntax : SyntaxNode where TConditionalExpressionSyntax : TExpressionSyntax { internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; protected abstract AbstractFormattingRule GetMultiLineFormattingRule(); #if CODE_STYLE protected abstract ISyntaxFormattingService GetSyntaxFormattingService(); #endif protected abstract TExpressionSyntax ConvertToExpression(IThrowOperation throwOperation); protected abstract TStatementSyntax WrapWithBlockIfAppropriate(TIfStatementSyntax ifStatement, TStatementSyntax statement); protected abstract Task FixOneAsync( Document document, Diagnostic diagnostic, SyntaxEditor editor, CancellationToken cancellationToken); protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // Defer to our callback to actually make the edits for each diagnostic. In turn, it // will return 'true' if it made a multi-line conditional expression. In that case, // we'll need to explicitly format this node so we can get our special multi-line // formatting in VB and C#. var nestedEditor = new SyntaxEditor(root, document.Project.Solution.Workspace); foreach (var diagnostic in diagnostics) { await FixOneAsync( document, diagnostic, nestedEditor, cancellationToken).ConfigureAwait(false); } var changedRoot = nestedEditor.GetChangedRoot(); // Get the language specific rule for formatting this construct and call into the // formatted to explicitly format things. Note: all we will format is the new // conditional expression as that's the only node that has the appropriate // annotation on it. var rules = new List<AbstractFormattingRule> { GetMultiLineFormattingRule() }; var options = document.Project.AnalyzerOptions.GetAnalyzerOptionSet(root.SyntaxTree, cancellationToken); #if CODE_STYLE var formattedRoot = FormatterHelper.Format(changedRoot, GetSyntaxFormattingService(), SpecializedFormattingAnnotation, options, rules, cancellationToken); #else var formattedRoot = Formatter.Format(changedRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options, rules, cancellationToken); #endif changedRoot = formattedRoot; editor.ReplaceNode(root, changedRoot); } /// <summary> /// Helper to create a conditional expression out of two original IOperation values /// corresponding to the whenTrue and whenFalse parts. The helper will add the appropriate /// annotations and casts to ensure that the conditional expression preserves semantics, but /// is also properly simplified and formatted. /// </summary> protected async Task<TExpressionSyntax> CreateConditionalExpressionAsync( Document document, IConditionalOperation ifOperation, IOperation trueStatement, IOperation falseStatement, IOperation trueValue, IOperation falseValue, bool isRef, CancellationToken cancellationToken) { var generator = SyntaxGenerator.GetGenerator(document); var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var condition = ifOperation.Condition.Syntax; if (!isRef) { // If we are going to generate "expr ? true : false" then just generate "expr" // instead. if (IsBooleanLiteral(trueValue, true) && IsBooleanLiteral(falseValue, false)) { return (TExpressionSyntax)condition.WithoutTrivia(); } // If we are going to generate "expr ? false : true" then just generate "!expr" // instead. if (IsBooleanLiteral(trueValue, false) && IsBooleanLiteral(falseValue, true)) { return (TExpressionSyntax)generator.Negate(generatorInternal, condition, semanticModel, cancellationToken).WithoutTrivia(); } } var conditionalExpression = (TConditionalExpressionSyntax)generator.ConditionalExpression( condition.WithoutTrivia(), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, trueStatement, trueValue)), MakeRef(generatorInternal, isRef, CastValueIfNecessary(generator, falseStatement, falseValue))); conditionalExpression = conditionalExpression.WithAdditionalAnnotations(Simplifier.Annotation); var makeMultiLine = await MakeMultiLineAsync( document, condition, trueValue.Syntax, falseValue.Syntax, cancellationToken).ConfigureAwait(false); if (makeMultiLine) { conditionalExpression = conditionalExpression.WithAdditionalAnnotations( SpecializedFormattingAnnotation); } return MakeRef(generatorInternal, isRef, conditionalExpression); } private static bool IsBooleanLiteral(IOperation trueValue, bool val) { if (trueValue is ILiteralOperation) { var constant = trueValue.ConstantValue; return constant.HasValue && constant.Value is bool b && b == val; } return false; } private static TExpressionSyntax MakeRef(SyntaxGeneratorInternal generator, bool isRef, TExpressionSyntax syntaxNode) => isRef ? (TExpressionSyntax)generator.RefExpression(syntaxNode) : syntaxNode; /// <summary> /// Checks if we should wrap the conditional expression over multiple lines. /// </summary> private static async Task<bool> MakeMultiLineAsync( Document document, SyntaxNode condition, SyntaxNode trueSyntax, SyntaxNode falseSyntax, CancellationToken cancellationToken) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (!sourceText.AreOnSameLine(condition.GetFirstToken(), condition.GetLastToken()) || !sourceText.AreOnSameLine(trueSyntax.GetFirstToken(), trueSyntax.GetLastToken()) || !sourceText.AreOnSameLine(falseSyntax.GetFirstToken(), falseSyntax.GetLastToken())) { return true; } #if CODE_STYLE var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = document.Project.AnalyzerOptions.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength, document.Project.Language, tree, cancellationToken); #else var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var wrappingLength = options.GetOption(UseConditionalExpressionOptions.ConditionalExpressionWrappingLength); #endif if (condition.Span.Length + trueSyntax.Span.Length + falseSyntax.Span.Length > wrappingLength) { return true; } return false; } private TExpressionSyntax CastValueIfNecessary( SyntaxGenerator generator, IOperation statement, IOperation value) { if (statement is IThrowOperation throwOperation) return ConvertToExpression(throwOperation); var sourceSyntax = value.Syntax.WithoutTrivia(); // If there was an implicit conversion generated by the compiler, then convert that to an // explicit conversion inside the condition. This is needed as there is no type // inference in conditional expressions, so we need to ensure that the same conversions // that were occurring previously still occur after conversion. Note: the simplifier // will remove any of these casts that are unnecessary. if (value is IConversionOperation conversion && conversion.IsImplicit && conversion.Type != null && conversion.Type.TypeKind != TypeKind.Error) { // Note we only add the cast if the source had no type (like the null literal), or a // non-error type itself. We don't want to insert lots of casts in error code. if (conversion.Operand.Type == null || conversion.Operand.Type.TypeKind != TypeKind.Error) { return (TExpressionSyntax)generator.CastExpression(conversion.Type, sourceSyntax); } } return (TExpressionSyntax)sourceSyntax; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Solution/Checksum_Factory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { // various factory methods. all these are just helper methods internal partial class Checksum { private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool = new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20); public static Checksum Create(IEnumerable<string> values) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; foreach (var value in values) { AppendData(hash, pooledBuffer.Object, value); AppendData(hash, pooledBuffer.Object, "\0"); } return From(hash.GetHashAndReset()); } public static Checksum Create(string value) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; AppendData(hash, pooledBuffer.Object, value); return From(hash.GetHashAndReset()); } public static Checksum Create(Stream stream) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; var buffer = pooledBuffer.Object; var bufferLength = buffer.Length; int bytesRead; do { bytesRead = stream.Read(buffer, 0, bufferLength); if (bytesRead > 0) { hash.AppendData(buffer, 0, bytesRead); } } while (bytesRead > 0); var bytes = hash.GetHashAndReset(); // if bytes array is bigger than certain size, checksum // will truncate it to predetermined size. for more detail, // see the Checksum type // // the truncation can happen since different hash algorithm or // same algorithm on different platform can have different hash size // which might be bigger than the Checksum HashSize. // // hash algorithm used here should remain functionally correct even // after the truncation return From(bytes); } public static Checksum Create(WellKnownSynchronizationKind kind, IObjectWritable @object) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)kind); @object.WriteTo(objectWriter); } stream.Position = 0; return Create(stream); } public static Checksum Create(WellKnownSynchronizationKind kind, IEnumerable<Checksum> checksums) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteInt32((int)kind); foreach (var checksum in checksums) { checksum.WriteTo(writer); } } stream.Position = 0; return Create(stream); } public static Checksum Create(WellKnownSynchronizationKind kind, ImmutableArray<byte> bytes) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteInt32((int)kind); for (var i = 0; i < bytes.Length; i++) { writer.WriteByte(bytes[i]); } } stream.Position = 0; return Create(stream); } public static Checksum Create<T>(WellKnownSynchronizationKind kind, T value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)kind); serializer.Serialize(value, objectWriter, context, CancellationToken.None); } stream.Position = 0; return Create(stream); } public static Checksum Create(ParseOptions value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)WellKnownSynchronizationKind.ParseOptions); serializer.SerializeParseOptions(value, objectWriter); } stream.Position = 0; return Create(stream); } private static void AppendData(IncrementalHash hash, byte[] buffer, string value) { var stringBytes = MemoryMarshal.AsBytes(value.AsSpan()); Debug.Assert(stringBytes.Length == value.Length * 2); var index = 0; while (index < stringBytes.Length) { var remaining = stringBytes.Length - index; var toCopy = Math.Min(remaining, buffer.Length); stringBytes.Slice(index, toCopy).CopyTo(buffer); hash.AppendData(buffer, 0, toCopy); index += toCopy; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; using System.Diagnostics; namespace Microsoft.CodeAnalysis { // various factory methods. all these are just helper methods internal partial class Checksum { private static readonly ObjectPool<IncrementalHash> s_incrementalHashPool = new(() => IncrementalHash.CreateHash(HashAlgorithmName.SHA256), size: 20); public static Checksum Create(IEnumerable<string> values) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; foreach (var value in values) { AppendData(hash, pooledBuffer.Object, value); AppendData(hash, pooledBuffer.Object, "\0"); } return From(hash.GetHashAndReset()); } public static Checksum Create(string value) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; AppendData(hash, pooledBuffer.Object, value); return From(hash.GetHashAndReset()); } public static Checksum Create(Stream stream) { using var pooledHash = s_incrementalHashPool.GetPooledObject(); using var pooledBuffer = SharedPools.ByteArray.GetPooledObject(); var hash = pooledHash.Object; var buffer = pooledBuffer.Object; var bufferLength = buffer.Length; int bytesRead; do { bytesRead = stream.Read(buffer, 0, bufferLength); if (bytesRead > 0) { hash.AppendData(buffer, 0, bytesRead); } } while (bytesRead > 0); var bytes = hash.GetHashAndReset(); // if bytes array is bigger than certain size, checksum // will truncate it to predetermined size. for more detail, // see the Checksum type // // the truncation can happen since different hash algorithm or // same algorithm on different platform can have different hash size // which might be bigger than the Checksum HashSize. // // hash algorithm used here should remain functionally correct even // after the truncation return From(bytes); } public static Checksum Create(WellKnownSynchronizationKind kind, IObjectWritable @object) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)kind); @object.WriteTo(objectWriter); } stream.Position = 0; return Create(stream); } public static Checksum Create(WellKnownSynchronizationKind kind, IEnumerable<Checksum> checksums) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteInt32((int)kind); foreach (var checksum in checksums) { checksum.WriteTo(writer); } } stream.Position = 0; return Create(stream); } public static Checksum Create(WellKnownSynchronizationKind kind, ImmutableArray<byte> bytes) { using var stream = SerializableBytes.CreateWritableStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteInt32((int)kind); for (var i = 0; i < bytes.Length; i++) { writer.WriteByte(bytes[i]); } } stream.Position = 0; return Create(stream); } public static Checksum Create<T>(WellKnownSynchronizationKind kind, T value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using var context = SolutionReplicationContext.Create(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)kind); serializer.Serialize(value, objectWriter, context, CancellationToken.None); } stream.Position = 0; return Create(stream); } public static Checksum Create(ParseOptions value, ISerializerService serializer) { using var stream = SerializableBytes.CreateWritableStream(); using (var objectWriter = new ObjectWriter(stream, leaveOpen: true)) { objectWriter.WriteInt32((int)WellKnownSynchronizationKind.ParseOptions); serializer.SerializeParseOptions(value, objectWriter); } stream.Position = 0; return Create(stream); } private static void AppendData(IncrementalHash hash, byte[] buffer, string value) { var stringBytes = MemoryMarshal.AsBytes(value.AsSpan()); Debug.Assert(stringBytes.Length == value.Length * 2); var index = 0; while (index < stringBytes.Length) { var remaining = stringBytes.Length - index; var toCopy = Math.Min(remaining, buffer.Length); stringBytes.Slice(index, toCopy).CopyTo(buffer); hash.AppendData(buffer, 0, toCopy); index += toCopy; } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CoreTestUtilities/Fakes/MockWorkspaceEventListenerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Test.Utilities { // mock default workspace event listener so that we don't try to enable solution crawler and etc implicitly [ExportWorkspaceServiceFactory(typeof(IWorkspaceEventListenerService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal sealed class MockWorkspaceEventListenerProvider : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public MockWorkspaceEventListenerProvider() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => 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.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Test.Utilities { // mock default workspace event listener so that we don't try to enable solution crawler and etc implicitly [ExportWorkspaceServiceFactory(typeof(IWorkspaceEventListenerService), ServiceLayer.Test), Shared, PartNotDiscoverable] internal sealed class MockWorkspaceEventListenerProvider : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, true)] public MockWorkspaceEventListenerProvider() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => null; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/PDB/PDBTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBTests : CSharpPDBTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; #region General [Fact] public void EmitDebugInfoForSourceTextWithoutEncoding1() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs"); var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: ""); var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs"); var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs"); var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream()); result.Diagnostics.Verify( // Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding. Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1), // Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding. Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitDebugInfoForSourceTextWithoutEncoding2() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs"); var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: ""); var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs"); var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs"); var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream()); result.Diagnostics.Verify(); Assert.True(result.Success); var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray(); var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray(); var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" /> <file id=""2"" name="""" language=""C#"" /> <file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" /> <file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" /> </files> </symbols>", options: PdbValidationOptions.ExcludeMethods); } [WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")] [ConditionalFact(typeof(WindowsOnly))] public void RelativePathForExternalSource_Sha1_Windows() { var text1 = WithWindowsLineBreaks(@" #pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081"" public class C { public void InitializeComponent() { #line 4 ""..\Test2.cs"" InitializeComponent(); #line default } } "); var compilation = CreateCompilation( new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") }, options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" /> <file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" /> </files> <methods> <method containingType=""C"" name=""InitializeComponent""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")] [ConditionalFact(typeof(UnixLikeOnly))] public void RelativePathForExternalSource_Sha1_Unix() { var text1 = WithWindowsLineBreaks(@" #pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081"" public class C { public void InitializeComponent() { #line 4 ""../Test2.cs"" InitializeComponent(); #line default } } "); var compilation = CreateCompilation( new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") }, options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" /> <file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" /> </files> <methods> <method containingType=""C"" name=""InitializeComponent""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors2() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>'' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>"))); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors3() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true)); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>'' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>"))); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors4() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'xxx' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx")); Assert.False(result.Success); } [WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")] [Fact] public void SuppressDynamicAndEncCDIForWinRT() { var source = @" public class C { public static void F() { dynamic a = 1; int b = 2; foreach (var x in new[] { 1,2,3 }) { System.Console.WriteLine(a * b); } } } "; var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD); debug.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" /> <entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xf5""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" /> <scope startOffset=""0x24"" endOffset=""0xe7""> <local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD); release.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" /> <entry offset=""0xdd"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xeb""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); } [WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")] [Fact] public void SuppressTupleElementNamesCDIForWinRT() { var source = @"class C { static void F() { (int A, int B) o = (1, 2); } }"; var debug = CreateCompilation(source, options: TestOptions.DebugWinMD); debug.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD); release.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); } [Fact] public void DuplicateDocuments() { var source1 = @"class C { static void F() { } }"; var source2 = @"class D { static void F() { } }"; var tree1 = Parse(source1, @"foo.cs"); var tree2 = Parse(source2, @"foo.cs"); var comp = CreateCompilation(new[] { tree1, tree2 }); // the first file wins (checksum CB 22 ...) comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void CustomDebugEntryPoint_DLL() { var source = @"class C { static void F() { } }"; var c = CreateCompilation(source, options: TestOptions.DebugDll); var f = c.GetMember<MethodSymbol>("C.F"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""F"" /> <methods/> </symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation); var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol())); int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress; Assert.Equal(0, peEntryPointToken); } [Fact] public void CustomDebugEntryPoint_EXE() { var source = @"class M { static void Main() { } } class C { static void F<S>() { } }"; var c = CreateCompilation(source, options: TestOptions.DebugExe); var f = c.GetMember<MethodSymbol>("C.F"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""F"" /> <methods/> </symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation); var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol())); int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress; var mdReader = peReader.GetMetadataReader(); var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken)); Assert.Equal("Main", mdReader.GetString(methodDef.Name)); } [Fact] public void CustomDebugEntryPoint_Errors() { var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }"; var source2 = @"class C { static void F() { } }"; var c1 = CreateCompilation(source1, options: TestOptions.DebugDll); var c2 = CreateCompilation(source2, options: TestOptions.DebugDll); var f1 = c1.GetMember<MethodSymbol>("C.F"); var f2 = c2.GetMember<MethodSymbol>("C.F"); var g = c1.GetMember<MethodSymbol>("D.G"); var d = c1.GetMember<NamedTypeSymbol>("D"); Assert.NotNull(f1); Assert.NotNull(f2); Assert.NotNull(g); Assert.NotNull(d); var stInt = c1.GetSpecialType(SpecialType.System_Int32); var d_t_g_int = g.Construct(stInt); var d_int = d.Construct(stInt); var d_int_g = d_int.GetMember<MethodSymbol>("G"); var d_int_g_int = d_int_g.Construct(stInt); var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); } [Fact] [WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")] public void TestLargeLineDelta() { var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000)); var source = $@" class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.PortablePdb); // Native PDBs only support spans with line delta <= 127 (7 bit) // https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621 c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); } [Fact] [WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")] public void TestLargeStartAndEndColumn_SameLine() { var spaces = new string(' ', 0x10000); var source = $@" class C {{ public static void Main() => {spaces}System.Console.WriteLine(""{spaces}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] [WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")] public void TestLargeStartAndEndColumn_DifferentLine() { var spaces = new string(' ', 0x10000); var source = $@" class C {{ public static void Main() => {spaces}System.Console.WriteLine( ""{spaces}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } #endregion #region Method Bodies [Fact] public void TestBasic() { var source = WithWindowsLineBreaks(@" class Program { Program() { } static void Main(string[] args) { Program p = new Program(); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Program"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestSimpleLocals() { var source = WithWindowsLineBreaks(@" class C { void Method() { //local at method scope object version = 6; System.Console.WriteLine(""version {0}"", version); { //a scope that defines no locals { //a nested local object foob = 1; System.Console.WriteLine(""foob {0}"", foob); } { //a nested local int foob1 = 1; System.Console.WriteLine(""foob1 {0}"", foob1); } System.Console.WriteLine(""Eva""); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Method", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Method""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""246"" /> <slot kind=""0"" offset=""402"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" /> <entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" /> <entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" /> <entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" /> <entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" /> <entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" /> <entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4c""> <local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" /> <scope startOffset=""0x15"" endOffset=""0x2a""> <local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" /> </scope> <scope startOffset=""0x2a"" endOffset=""0x3f""> <local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")] public void ConstructorsWithoutInitializers() { var source = WithWindowsLineBreaks( @"class C { C() { object o; } C(object x) { object y = x; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <scope startOffset=""0x7"" endOffset=""0xb""> <local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")] [Fact] public void ConstructorsWithInitializers() { var source = WithWindowsLineBreaks( @"class C { static object G = 1; object F = G; C() { object o; } C(object x) { object y = x; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" /> <entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" /> <entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <scope startOffset=""0x12"" endOffset=""0x14""> <local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" /> <entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <scope startOffset=""0x12"" endOffset=""0x16""> <local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } /// <summary> /// Although the debugging info attached to DebuggerHidden method is not used by the debugger /// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we. /// /// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method. /// NonUserCode method needs the information if JustMyCode is disabled. /// /// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not. /// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace. /// </summary> [Fact] public void MethodsWithDebuggerAttributes() { var source = WithWindowsLineBreaks(@" using System; using System.Diagnostics; class Program { [DebuggerHidden] static void Hidden() { int x = 1; Console.WriteLine(x); } [DebuggerStepThrough] static void StepThrough() { int y = 1; Console.WriteLine(y); } [DebuggerNonUserCode] static void NonUserCode() { int z = 1; Console.WriteLine(z); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Hidden""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </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=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <namespace name=""System"" /> <namespace name=""System.Diagnostics"" /> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> <method containingType=""Program"" name=""StepThrough""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Hidden"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> <method containingType=""Program"" name=""NonUserCode""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Hidden"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } /// <summary> /// If a synthesized method contains any user code, /// the method must have a sequence point at /// offset 0 for correct stepping behavior. /// </summary> [WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")] [Fact] public void SequencePointAtOffset0() { string source = WithWindowsLineBreaks( @"using System; class C { static Func<object, int> F = x => { Func<object, int> f = o => 1; Func<Func<object, int>, Func<object, int>> g = h => y => h(y); return g(f)(null); }; }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".cctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-45"" /> <lambda offset=""-147"" /> <lambda offset=""-109"" /> <lambda offset=""-45"" /> <lambda offset=""-40"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <namespace name=""System"" /> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass2_0"" name=""&lt;.cctor&gt;b__3"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""-118"" /> <slot kind=""0"" offset=""-54"" /> <slot kind=""21"" offset=""-147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" /> <entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x53""> <local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> <local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_1"" parameterNames=""o""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_2"" parameterNames=""h""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-45"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Leading trivia is not included in the syntax offset. /// </summary> [Fact] public void SyntaxOffsetInPresenceOfTrivia_Methods() { string source = @" class C { public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/ public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/ }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // verify that both syntax offsets are the same c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main1""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" /> <entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""C"" name=""Main2""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" /> <entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Leading and trailing trivia are not included in the syntax offset. /// </summary> [Fact] public void SyntaxOffsetInPresenceOfTrivia_Initializers() { string source = @" using System; class C1 { public static Func<int> e=() => 0; public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/ public static Func<int> g=() => 2; } class C2 { public static Func<int> e=() => 0; public static Func<int> f=/*Comment1*/() => 1; public static Func<int> g=() => 2; } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // verify that syntax offsets of both .cctor's are the same c.VerifyPdb("C1..cctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C1"" name="".cctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <lambda offset=""-29"" /> <lambda offset=""-9"" /> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" /> <entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" /> <entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); c.VerifyPdb("C2..cctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C2"" name="".cctor""> <customDebugInfo> <forward declaringType=""C1"" methodName="".cctor"" /> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <lambda offset=""-29"" /> <lambda offset=""-9"" /> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" /> <entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region ReturnStatement [Fact] public void Return_Method1() { var source = WithWindowsLineBreaks(@" class Program { static int Main() { return 1; } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); // In order to place a breakpoint on the closing brace we need to save the return expression value to // a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived. v.VerifyIL("Program.Main", @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0005 -IL_0005: ldloc.0 IL_0006: ret }", sequencePoints: "Program.Main"); v.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Property1() { var source = WithWindowsLineBreaks(@" class C { static int P { get { return 1; } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); // In order to place a breakpoint on the closing brace we need to save the return expression value to // a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived. v.VerifyIL("C.P.get", @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0005 -IL_0005: ldloc.0 IL_0006: ret }", sequencePoints: "C.get_P"); v.VerifyPdb("C.get_P", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Void1() { var source = @" class Program { static void Main() { return; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 4 (0x4) .maxstack 0 -IL_0000: nop -IL_0001: br.s IL_0003 -IL_0003: ret }", sequencePoints: "Program.Main"); } [Fact] public void Return_ExpressionBodied1() { var source = @" class Program { static int Main() => 1; } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 2 (0x2) .maxstack 1 -IL_0000: ldc.i4.1 IL_0001: ret }", sequencePoints: "Program.Main"); } [Fact] public void Return_FromExceptionHandler1() { var source = WithWindowsLineBreaks(@" using System; class Program { static int Main() { try { Console.WriteLine(); return 1; } catch (Exception) { return 2; } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: call ""void System.Console.WriteLine()"" IL_0007: nop -IL_0008: ldc.i4.1 IL_0009: stloc.0 IL_000a: leave.s IL_0012 } catch System.Exception { -IL_000c: pop -IL_000d: nop -IL_000e: ldc.i4.2 IL_000f: stloc.0 IL_0010: leave.s IL_0012 } -IL_0012: ldloc.0 IL_0013: ret }", sequencePoints: "Program.Main"); v.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } #endregion #region IfStatement [Fact] public void IfStatement() { var source = WithWindowsLineBreaks(@" class C { void Method() { bool b = true; if (b) { string s = ""true""; System.Console.WriteLine(s); } else { string s = ""false""; int i = 1; while (i < 100) { int j = i, k = 1; System.Console.WriteLine(j); i = j + k; } i = i + 1; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Method", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Method""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""1"" offset=""38"" /> <slot kind=""0"" offset=""76"" /> <slot kind=""0"" offset=""188"" /> <slot kind=""0"" offset=""218"" /> <slot kind=""0"" offset=""292"" /> <slot kind=""0"" offset=""299"" /> <slot kind=""1"" offset=""240"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" /> <entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" /> <entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" /> <entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" /> <entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" /> <entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" /> <entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" /> <entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> <entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x51""> <local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" /> <scope startOffset=""0x8"" endOffset=""0x17""> <local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" /> </scope> <scope startOffset=""0x19"" endOffset=""0x50""> <local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" /> <local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" /> <scope startOffset=""0x25"" endOffset=""0x3d""> <local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" /> <local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region WhileStatement [WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")] [Fact] public void WhileStatement() { var source = @"using System; public class SeqPointForWhile { public static void Main() { SeqPointForWhile obj = new SeqPointForWhile(); obj.While(234); } int field; public void While(int p) { while (p > 0) // SeqPt should be generated at the end of loop { p = (int)(p / 2); if (p > 100) { continue; } else if (p > 10) { int x = p; field = x; } else { int x = p; Console.WriteLine(x); break; } } field = -1; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); // Offset 0x01 should be: // <entry offset=""0x1"" hidden=""true"" document=""1"" /> // Move original offset 0x01 to 0x33 // <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" /> // // Note: 16707566 == 0x00FEEFEE c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" /> <methods> <method containingType=""SeqPointForWhile"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <namespace name=""System"" /> </scope> </method> <method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointForWhile"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" /> <entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" /> <entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" /> <entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" /> <entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" /> <entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x30""> <scope startOffset=""0x11"" endOffset=""0x1a""> <local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region ForStatement [Fact] public void ForStatement1() { var source = WithWindowsLineBreaks(@" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""i"" /> <encLocalSlotMap> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x20""> <scope startOffset=""0x1"" endOffset=""0x1f""> <local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void ForStatement2() { var source = @" class C { static void M() { for (;;) { System.Console.WriteLine(1); } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void ForStatement3() { var source = WithWindowsLineBreaks(@" class C { static void M() { int i = 0; for (;;i++) { System.Console.WriteLine(i); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" /> <entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region ForEachStatement [Fact] public void ForEachStatement_String() { var source = @" public class C { public static void Main() { foreach (var c in ""hello"") { System.Console.WriteLine(c); } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) '"hello"' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) Hidden index increment. // 10) 'in' // 11) Close brace at end of method c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ForEachStatement_Array() { var source = WithWindowsLineBreaks(@" public class C { public static void Main() { foreach (var x in new int[2]) { System.Console.WriteLine(x); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new int[2]' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) Hidden index increment. // 10) 'in' // 11) Close brace at end of method c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x25""> <scope startOffset=""0xd"" endOffset=""0x1a""> <local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")] [Fact] public void ForEachStatement_MultiDimensionalArray() { var source = @" public class C { public static void Main() { foreach (var x in new int[2, 3]) { System.Console.WriteLine(x); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new int[2, 3]' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) 'in' // 10) Close brace at end of method v.VerifyIL("C.Main", @" { // Code size 88 (0x58) .maxstack 3 .locals init (int[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.2 IL_0003: ldc.i4.3 IL_0004: newobj ""int[*,*]..ctor"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldc.i4.0 IL_000c: callvirt ""int System.Array.GetUpperBound(int)"" IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: ldc.i4.1 IL_0014: callvirt ""int System.Array.GetUpperBound(int)"" IL_0019: stloc.2 IL_001a: ldloc.0 IL_001b: ldc.i4.0 IL_001c: callvirt ""int System.Array.GetLowerBound(int)"" IL_0021: stloc.3 ~IL_0022: br.s IL_0053 IL_0024: ldloc.0 IL_0025: ldc.i4.1 IL_0026: callvirt ""int System.Array.GetLowerBound(int)"" IL_002b: stloc.s V_4 ~IL_002d: br.s IL_004a -IL_002f: ldloc.0 IL_0030: ldloc.3 IL_0031: ldloc.s V_4 IL_0033: call ""int[*,*].Get"" IL_0038: stloc.s V_5 -IL_003a: nop -IL_003b: ldloc.s V_5 IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: nop -IL_0043: nop ~IL_0044: ldloc.s V_4 IL_0046: ldc.i4.1 IL_0047: add IL_0048: stloc.s V_4 -IL_004a: ldloc.s V_4 IL_004c: ldloc.2 IL_004d: ble.s IL_002f ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.1 IL_0055: ble.s IL_0024 -IL_0057: ret } ", sequencePoints: "C.Main"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInAsyncMethod() { var source = WithWindowsLineBreaks(@" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console .WriteLine(); } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 81 (0x51) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 // sequence point: Console ... .WriteLine() IL_001c: call ""void System.Console.WriteLine()"" IL_0021: nop // sequence point: <hidden> IL_0022: leave.s IL_003c } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0024: stloc.2 IL_0025: ldarg.0 IL_0026: ldc.i4.s -2 IL_0028: stfld ""int Program.<Test>d__0.<>1__state"" IL_002d: ldarg.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0033: ldloc.2 IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0039: nop IL_003a: leave.s IL_0050 } // sequence point: } IL_003c: ldarg.0 IL_003d: ldc.i4.s -2 IL_003f: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_004f: nop IL_0050: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <forwardIterator name=""&lt;Test&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program+&lt;Test&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x51"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""1"" offset=""33"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x51""> <namespace name=""System"" /> </scope> <asyncInfo> <catchHandler offset=""0x24"" /> <kickoffMethod declaringType=""Program"" methodName=""Test"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalBeforeLocalFunction() { var source = @" class C { void M() { int i = 0; if (i != 0) { return; } string local() { throw null; } System.Console.Write(1); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: if (i != 0) IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: cgt.un IL_0007: stloc.1 // sequence point: <hidden> IL_0008: ldloc.1 IL_0009: brfalse.s IL_000e // sequence point: { IL_000b: nop // sequence point: return; IL_000c: br.s IL_0016 // sequence point: <hidden> IL_000e: nop // sequence point: System.Console.Write(1); IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: nop // sequence point: } IL_0016: ret } ", sequencePoints: "C.M", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInAsyncMethodWithExplicitReturn() { var source = @" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console .WriteLine(); return; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 81 (0x51) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 // sequence point: Console ... .WriteLine() IL_001c: call ""void System.Console.WriteLine()"" IL_0021: nop // sequence point: return; IL_0022: leave.s IL_003c } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0024: stloc.2 IL_0025: ldarg.0 IL_0026: ldc.i4.s -2 IL_0028: stfld ""int Program.<Test>d__0.<>1__state"" IL_002d: ldarg.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0033: ldloc.2 IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0039: nop IL_003a: leave.s IL_0050 } // sequence point: } IL_003c: ldarg.0 IL_003d: ldc.i4.s -2 IL_003f: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_004f: nop IL_0050: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInSimpleMethod() { var source = @" using System; class Program { public static void Test() { int i = 0; if (i != 0) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Test()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: if (i != 0) IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: cgt.un IL_0007: stloc.1 // sequence point: <hidden> IL_0008: ldloc.1 IL_0009: brfalse.s IL_0011 // sequence point: Console.WriteLine(); IL_000b: call ""void System.Console.WriteLine()"" IL_0010: nop // sequence point: } IL_0011: ret } ", sequencePoints: "Program.Test", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ElseConditionalInAsyncMethod() { var source = WithWindowsLineBreaks(@" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console.WriteLine(""one""); else Console.WriteLine(""other""); } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 99 (0x63) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0029 // sequence point: Console.WriteLine(""one""); IL_001c: ldstr ""one"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: nop // sequence point: <hidden> IL_0027: br.s IL_0034 // sequence point: Console.WriteLine(""other""); IL_0029: ldstr ""other"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: nop // sequence point: <hidden> IL_0034: leave.s IL_004e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0036: stloc.2 IL_0037: ldarg.0 IL_0038: ldc.i4.s -2 IL_003a: stfld ""int Program.<Test>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0045: ldloc.2 IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_004b: nop IL_004c: leave.s IL_0062 } // sequence point: } IL_004e: ldarg.0 IL_004f: ldc.i4.s -2 IL_0051: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0061: nop IL_0062: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <forwardIterator name=""&lt;Test&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program+&lt;Test&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x63"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""1"" offset=""33"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" /> <entry offset=""0x34"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x63""> <namespace name=""System"" /> </scope> <asyncInfo> <catchHandler offset=""0x36"" /> <kickoffMethod declaringType=""Program"" methodName=""Test"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInTry() { var source = WithWindowsLineBreaks(@" using System; class Program { public static void Test() { try { int i = 0; if (i != 0) Console.WriteLine(); } catch { } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Test", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop .try { // sequence point: { IL_0001: nop // sequence point: int i = 0; IL_0002: ldc.i4.0 IL_0003: stloc.0 // sequence point: if (i != 0) IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: cgt.un IL_0008: stloc.1 // sequence point: <hidden> IL_0009: ldloc.1 IL_000a: brfalse.s IL_0012 // sequence point: Console.WriteLine(); IL_000c: call ""void System.Console.WriteLine()"" IL_0011: nop // sequence point: } IL_0012: nop IL_0013: leave.s IL_001a } catch object { // sequence point: catch IL_0015: pop // sequence point: { IL_0016: nop // sequence point: } IL_0017: nop IL_0018: leave.s IL_001a } // sequence point: } IL_001a: ret } ", sequencePoints: "Program.Test", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""43"" /> <slot kind=""1"" offset=""65"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" /> <entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" /> <entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" /> <entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x13""> <local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")] [Fact] public void ForEachStatement_MultiDimensionalArrayBreakAndContinue() { var source = @" using System; class C { static void Main() { int[, ,] array = new[,,] { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} }, }; foreach (int i in array) { if (i % 2 == 1) continue; if (i > 4) break; Console.WriteLine(i); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE")); // Stepping: // After "continue", step to "in". // After "break", step to first sequence point following loop body (in this case, method close brace). v.VerifyIL("C.Main", @" { // Code size 169 (0xa9) .maxstack 4 .locals init (int[,,] V_0, //array int[,,] V_1, int V_2, int V_3, int V_4, int V_5, int V_6, int V_7, int V_8, //i bool V_9, bool V_10) -IL_0000: nop -IL_0001: ldc.i4.2 IL_0002: ldc.i4.2 IL_0003: ldc.i4.2 IL_0004: newobj ""int[*,*,*]..ctor"" IL_0009: dup IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18"" IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0014: stloc.0 -IL_0015: nop -IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ldc.i4.0 IL_001a: callvirt ""int System.Array.GetUpperBound(int)"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetUpperBound(int)"" IL_0027: stloc.3 IL_0028: ldloc.1 IL_0029: ldc.i4.2 IL_002a: callvirt ""int System.Array.GetUpperBound(int)"" IL_002f: stloc.s V_4 IL_0031: ldloc.1 IL_0032: ldc.i4.0 IL_0033: callvirt ""int System.Array.GetLowerBound(int)"" IL_0038: stloc.s V_5 ~IL_003a: br.s IL_00a3 IL_003c: ldloc.1 IL_003d: ldc.i4.1 IL_003e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0043: stloc.s V_6 ~IL_0045: br.s IL_0098 IL_0047: ldloc.1 IL_0048: ldc.i4.2 IL_0049: callvirt ""int System.Array.GetLowerBound(int)"" IL_004e: stloc.s V_7 ~IL_0050: br.s IL_008c -IL_0052: ldloc.1 IL_0053: ldloc.s V_5 IL_0055: ldloc.s V_6 IL_0057: ldloc.s V_7 IL_0059: call ""int[*,*,*].Get"" IL_005e: stloc.s V_8 -IL_0060: nop -IL_0061: ldloc.s V_8 IL_0063: ldc.i4.2 IL_0064: rem IL_0065: ldc.i4.1 IL_0066: ceq IL_0068: stloc.s V_9 ~IL_006a: ldloc.s V_9 IL_006c: brfalse.s IL_0070 -IL_006e: br.s IL_0086 -IL_0070: ldloc.s V_8 IL_0072: ldc.i4.4 IL_0073: cgt IL_0075: stloc.s V_10 ~IL_0077: ldloc.s V_10 IL_0079: brfalse.s IL_007d -IL_007b: br.s IL_00a8 -IL_007d: ldloc.s V_8 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop -IL_0085: nop ~IL_0086: ldloc.s V_7 IL_0088: ldc.i4.1 IL_0089: add IL_008a: stloc.s V_7 -IL_008c: ldloc.s V_7 IL_008e: ldloc.s V_4 IL_0090: ble.s IL_0052 ~IL_0092: ldloc.s V_6 IL_0094: ldc.i4.1 IL_0095: add IL_0096: stloc.s V_6 -IL_0098: ldloc.s V_6 IL_009a: ldloc.3 IL_009b: ble.s IL_0047 ~IL_009d: ldloc.s V_5 IL_009f: ldc.i4.1 IL_00a0: add IL_00a1: stloc.s V_5 -IL_00a3: ldloc.s V_5 IL_00a5: ldloc.2 IL_00a6: ble.s IL_003c -IL_00a8: ret } ", sequencePoints: "C.Main"); } [Fact] public void ForEachStatement_Enumerator() { var source = @" public class C { public static void Main() { foreach (var x in new System.Collections.Generic.List<int>()) { System.Console.WriteLine(x); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new System.Collections.Generic.List<int>()' // 4) Hidden initial jump (of while loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) 'in' // 10) hidden point in Finally // 11) Close brace at end of method v.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 1 .locals init (System.Collections.Generic.List<int>.Enumerator V_0, int V_1) //x -IL_0000: nop -IL_0001: nop -IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()"" IL_000c: stloc.0 .try { ~IL_000d: br.s IL_0020 -IL_000f: ldloca.s V_0 IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get"" IL_0016: stloc.1 -IL_0017: nop -IL_0018: ldloc.1 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop -IL_001f: nop -IL_0020: ldloca.s V_0 IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()"" IL_0027: brtrue.s IL_000f IL_0029: leave.s IL_003a } finally { ~IL_002b: ldloca.s V_0 IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator"" IL_0033: callvirt ""void System.IDisposable.Dispose()"" IL_0038: nop IL_0039: endfinally } -IL_003a: ret } ", sequencePoints: "C.Main"); } [WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")] [Fact] public void ForEachNops() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { foreach (var i in l.AsEnumerable()) { switch (i.Count) { case 1: break; default: if (i.Count != 0) { } break; } } } } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <encLocalSlotMap> <slot kind=""5"" offset=""15"" /> <slot kind=""0"" offset=""15"" /> <slot kind=""35"" offset=""83"" /> <slot kind=""1"" offset=""83"" /> <slot kind=""1"" offset=""237"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" /> <entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" /> <entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" /> <entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x55"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x57""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <scope startOffset=""0x14"" endOffset=""0x41""> <local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>" ); } [Fact] public void ForEachStatement_Deconstruction() { var source = WithWindowsLineBreaks(@" public class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void Main() { foreach (var (c, (d, e)) in F()) { System.Console.WriteLine(c); } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //c bool V_3, //d double V_4, //e System.ValueTuple<bool, double> V_5) // sequence point: { IL_0000: nop // sequence point: foreach IL_0001: nop // sequence point: F() IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 // sequence point: <hidden> IL_000a: br.s IL_003f // sequence point: var (c, (d, e)) IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 // sequence point: { IL_0032: nop // sequence point: System.Console.WriteLine(c); IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop // sequence point: } IL_003a: nop // sequence point: <hidden> IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 // sequence point: in IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c // sequence point: } IL_0045: ret } ", sequencePoints: "C.Main", source: source); v.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""25"" /> <slot kind=""0"" offset=""29"" /> <slot kind=""0"" offset=""32"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x46""> <scope startOffset=""0xc"" endOffset=""0x3b""> <local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> <local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> <local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region Switch [Fact] public void SwitchWithPattern_01() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static string Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""0"" offset=""59"" /> <slot kind=""0"" offset=""163"" /> <slot kind=""0"" offset=""250"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" /> <entry offset=""0x4f"" hidden=""true"" document=""1"" /> <entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" /> <entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" /> <entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xaa""> <scope startOffset=""0x1d"" endOffset=""0x4f""> <local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" /> </scope> <scope startOffset=""0x4f"" endOffset=""0x72""> <local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" /> </scope> <scope startOffset=""0x72"" endOffset=""0x93""> <local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchWithPattern_02() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static System.Func<string> Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: return () => $""Student {s.Name} ({s.GPA:N1})""; case Student s: return () => $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return () => $""Teacher {t.Name} of {t.Subject}""; default: return () => $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""109"" closure=""1"" /> <lambda offset=""202"" closure=""1"" /> <lambda offset=""295"" closure=""1"" /> <lambda offset=""383"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" /> <entry offset=""0x8d"" hidden=""true"" document=""1"" /> <entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" /> <entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" /> <entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb2""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xaf""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchWithPatternAndLocalFunctions() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static System.Func<string> Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: string f1() => $""Student {s.Name} ({s.GPA:N1})""; return f1; case Student s: string f2() => $""Student {s.Name} ({s.GPA:N1})""; return f2; case Teacher t: string f3() => $""Teacher {t.Name} of {t.Subject}""; return f3; default: string f4() => $""Person {p.Name}""; return f4; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""111"" closure=""1"" /> <lambda offset=""234"" closure=""1"" /> <lambda offset=""357"" closure=""1"" /> <lambda offset=""475"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" /> <entry offset=""0xa2"" hidden=""true"" document=""1"" /> <entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" /> <entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb6""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xb3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")] [Fact] public void SwitchWithConstantPattern() { string source = @" using System; class Program { static void Main(string[] args) { M1(); M2(); } static void M1() { switch (1) { case 0 when true: ; case 1: Console.Write(1); break; case 2: ; } } static void M2() { switch (nameof(M2)) { case nameof(M1) when true: ; case nameof(M2): Console.Write(nameof(M2)); break; case nameof(Main): ; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "1M2"); verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source, expectedIL: @"{ // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1) // sequence point: { IL_0000: nop // sequence point: switch ... (1 IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldc.i4.1 IL_0004: stloc.0 // sequence point: <hidden> IL_0005: br.s IL_0007 // sequence point: Console.Write(1); IL_0007: ldc.i4.1 IL_0008: call ""void System.Console.Write(int)"" IL_000d: nop // sequence point: break; IL_000e: br.s IL_0010 // sequence point: } IL_0010: ret }"); verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (string V_0, string V_1) // sequence point: { IL_0000: nop // sequence point: switch ... (nameof(M2) IL_0001: ldstr ""M2"" IL_0006: stloc.1 IL_0007: ldstr ""M2"" IL_000c: stloc.0 // sequence point: <hidden> IL_000d: br.s IL_000f // sequence point: Console.Write(nameof(M2)); IL_000f: ldstr ""M2"" IL_0014: call ""void System.Console.Write(string)"" IL_0019: nop // sequence point: break; IL_001a: br.s IL_001c // sequence point: } IL_001c: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "1M2"); verifier.VerifyIL("Program.M1", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""M2"" IL_0005: call ""void System.Console.Write(string)"" IL_000a: ret }"); } [WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")] [Fact] public void SwitchWithConstantGenericPattern_01() { string source = @" using System; class Program { static void Main(string[] args) { M1<int>(); // 1 M1<long>(); // 2 M2<string>(); // 3 M2<int>(); // 4 } static void M1<T>() { switch (1) { case T t: Console.Write(1); break; case int i: Console.Write(2); break; } } static void M2<T>() { switch (nameof(M2)) { case T t: Console.Write(3); break; case string s: Console.Write(4); break; case null: ; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "1234"); verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source, expectedIL: @"{ // Code size 60 (0x3c) .maxstack 1 .locals init (T V_0, //t int V_1, //i int V_2) // sequence point: { IL_0000: nop // sequence point: switch (1) IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldc.i4.1 IL_0004: stloc.1 // sequence point: <hidden> IL_0005: ldloc.1 IL_0006: box ""int"" IL_000b: isinst ""T"" IL_0010: brfalse.s IL_0030 IL_0012: ldloc.1 IL_0013: box ""int"" IL_0018: isinst ""T"" IL_001d: unbox.any ""T"" IL_0022: stloc.0 // sequence point: <hidden> IL_0023: br.s IL_0025 // sequence point: <hidden> IL_0025: br.s IL_0027 // sequence point: Console.Write(1); IL_0027: ldc.i4.1 IL_0028: call ""void System.Console.Write(int)"" IL_002d: nop // sequence point: break; IL_002e: br.s IL_003b // sequence point: <hidden> IL_0030: br.s IL_0032 // sequence point: Console.Write(2); IL_0032: ldc.i4.2 IL_0033: call ""void System.Console.Write(int)"" IL_0038: nop // sequence point: break; IL_0039: br.s IL_003b // sequence point: } IL_003b: ret }"); verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 58 (0x3a) .maxstack 1 .locals init (T V_0, //t string V_1, //s string V_2) // sequence point: { IL_0000: nop // sequence point: switch (nameof(M2)) IL_0001: ldstr ""M2"" IL_0006: stloc.2 IL_0007: ldstr ""M2"" IL_000c: stloc.1 // sequence point: <hidden> IL_000d: ldloc.1 IL_000e: isinst ""T"" IL_0013: brfalse.s IL_002e IL_0015: ldloc.1 IL_0016: isinst ""T"" IL_001b: unbox.any ""T"" IL_0020: stloc.0 // sequence point: <hidden> IL_0021: br.s IL_0023 // sequence point: <hidden> IL_0023: br.s IL_0025 // sequence point: Console.Write(3); IL_0025: ldc.i4.3 IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop // sequence point: break; IL_002c: br.s IL_0039 // sequence point: <hidden> IL_002e: br.s IL_0030 // sequence point: Console.Write(4); IL_0030: ldc.i4.4 IL_0031: call ""void System.Console.Write(int)"" IL_0036: nop // sequence point: break; IL_0037: br.s IL_0039 // sequence point: } IL_0039: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "1234"); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box ""int"" IL_0008: isinst ""T"" IL_000d: brfalse.s IL_0016 IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldc.i4.2 IL_0017: call ""void System.Console.Write(int)"" IL_001c: ret }"); verifier.VerifyIL("Program.M2<T>", @"{ // Code size 28 (0x1c) .maxstack 1 .locals init (string V_0) //s IL_0000: ldstr ""M2"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: isinst ""T"" IL_000c: brfalse.s IL_0015 IL_000e: ldc.i4.3 IL_000f: call ""void System.Console.Write(int)"" IL_0014: ret IL_0015: ldc.i4.4 IL_0016: call ""void System.Console.Write(int)"" IL_001b: ret }"); } [WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")] [Fact] public void SwitchWithConstantGenericPattern_02() { string source = @" using System; class Program { static void Main(string[] args) { M2<string>(); // 6 M2<int>(); // 6 } static void M2<T>() { const string x = null; switch (x) { case T t: ; case string s: ; case null: Console.Write(6); break; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "66"); verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 17 (0x11) .maxstack 1 .locals init (T V_0, //t string V_1, //s string V_2, string V_3) // sequence point: { IL_0000: nop // sequence point: switch (x) IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldnull IL_0004: stloc.2 // sequence point: <hidden> IL_0005: br.s IL_0007 // sequence point: Console.Write(6); IL_0007: ldc.i4.6 IL_0008: call ""void System.Console.Write(int)"" IL_000d: nop // sequence point: break; IL_000e: br.s IL_0010 // sequence point: } IL_0010: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "66"); verifier.VerifyIL("Program.M2<T>", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.6 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ret }"); } [Fact] [WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")] public void TestSequencePoints_31665() { var source = @" using System; internal class Program { private static void Main(string[] args) { var s = ""1""; if (true) switch (s) { case ""1"": Console.Out.WriteLine(""Input was 1""); break; default: throw new Exception(""Default case""); } else Console.Out.WriteLine(""Too many inputs""); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main(string[])", @" { // Code size 60 (0x3c) .maxstack 2 .locals init (string V_0, //s bool V_1, string V_2, string V_3) // sequence point: { IL_0000: nop // sequence point: var s = ""1""; IL_0001: ldstr ""1"" IL_0006: stloc.0 // sequence point: if (true) IL_0007: ldc.i4.1 IL_0008: stloc.1 // sequence point: switch (s) IL_0009: ldloc.0 IL_000a: stloc.3 // sequence point: <hidden> IL_000b: ldloc.3 IL_000c: stloc.2 // sequence point: <hidden> IL_000d: ldloc.2 IL_000e: ldstr ""1"" IL_0013: call ""bool string.op_Equality(string, string)"" IL_0018: brtrue.s IL_001c IL_001a: br.s IL_002e // sequence point: Console.Out.WriteLine(""Input was 1""); IL_001c: call ""System.IO.TextWriter System.Console.Out.get"" IL_0021: ldstr ""Input was 1"" IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)"" IL_002b: nop // sequence point: break; IL_002c: br.s IL_0039 // sequence point: throw new Exception(""Default case""); IL_002e: ldstr ""Default case"" IL_0033: newobj ""System.Exception..ctor(string)"" IL_0038: throw // sequence point: <hidden> IL_0039: br.s IL_003b // sequence point: } IL_003b: ret } ", sequencePoints: "Program.Main", source: source); } [Fact] [WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")] public void TestSequencePoints_17076() { var source = @" using System.Threading.Tasks; internal class Program { private static void Main(string[] args) { M(new Node()).GetAwaiter().GetResult(); } static async Task M(Node node) { while (node != null) { if (node is A a) { await Task.Yield(); return; } else if (node is B b) { await Task.Yield(); return; } node = node.Parent; } } } class Node { public Node Parent = null; } class A : Node { } class B : Node { } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 403 (0x193) .maxstack 3 .locals init (int V_0, bool V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, Program.<M>d__1 V_4, bool V_5, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6, bool V_7, System.Exception V_8) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_007e IL_0014: br IL_0109 // sequence point: { IL_0019: nop // sequence point: <hidden> IL_001a: br IL_0150 // sequence point: { IL_001f: nop // sequence point: if (node is A a) IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""Node Program.<M>d__1.node"" IL_0027: isinst ""A"" IL_002c: stfld ""A Program.<M>d__1.<a>5__1"" IL_0031: ldarg.0 IL_0032: ldfld ""A Program.<M>d__1.<a>5__1"" IL_0037: ldnull IL_0038: cgt.un IL_003a: stloc.1 // sequence point: <hidden> IL_003b: ldloc.1 IL_003c: brfalse.s IL_00a7 // sequence point: { IL_003e: nop // sequence point: await Task.Yield(); IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0044: stloc.3 IL_0045: ldloca.s V_3 IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_004c: stloc.2 // sequence point: <hidden> IL_004d: ldloca.s V_2 IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0054: brtrue.s IL_009a IL_0056: ldarg.0 IL_0057: ldc.i4.0 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<M>d__1.<>1__state"" // async: yield IL_005f: ldarg.0 IL_0060: ldloc.2 IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0066: ldarg.0 IL_0067: stloc.s V_4 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_006f: ldloca.s V_2 IL_0071: ldloca.s V_4 IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)"" IL_0078: nop IL_0079: leave IL_0192 // async: resume IL_007e: ldarg.0 IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0084: stloc.2 IL_0085: ldarg.0 IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0091: ldarg.0 IL_0092: ldc.i4.m1 IL_0093: dup IL_0094: stloc.0 IL_0095: stfld ""int Program.<M>d__1.<>1__state"" IL_009a: ldloca.s V_2 IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_00a1: nop // sequence point: return; IL_00a2: leave IL_017e // sequence point: if (node is B b) IL_00a7: ldarg.0 IL_00a8: ldarg.0 IL_00a9: ldfld ""Node Program.<M>d__1.node"" IL_00ae: isinst ""B"" IL_00b3: stfld ""B Program.<M>d__1.<b>5__2"" IL_00b8: ldarg.0 IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2"" IL_00be: ldnull IL_00bf: cgt.un IL_00c1: stloc.s V_5 // sequence point: <hidden> IL_00c3: ldloc.s V_5 IL_00c5: brfalse.s IL_0130 // sequence point: { IL_00c7: nop // sequence point: await Task.Yield(); IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_00cd: stloc.3 IL_00ce: ldloca.s V_3 IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_00d5: stloc.s V_6 // sequence point: <hidden> IL_00d7: ldloca.s V_6 IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_00de: brtrue.s IL_0126 IL_00e0: ldarg.0 IL_00e1: ldc.i4.1 IL_00e2: dup IL_00e3: stloc.0 IL_00e4: stfld ""int Program.<M>d__1.<>1__state"" // async: yield IL_00e9: ldarg.0 IL_00ea: ldloc.s V_6 IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_00f1: ldarg.0 IL_00f2: stloc.s V_4 IL_00f4: ldarg.0 IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_00fa: ldloca.s V_6 IL_00fc: ldloca.s V_4 IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)"" IL_0103: nop IL_0104: leave IL_0192 // async: resume IL_0109: ldarg.0 IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_010f: stloc.s V_6 IL_0111: ldarg.0 IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_011d: ldarg.0 IL_011e: ldc.i4.m1 IL_011f: dup IL_0120: stloc.0 IL_0121: stfld ""int Program.<M>d__1.<>1__state"" IL_0126: ldloca.s V_6 IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_012d: nop // sequence point: return; IL_012e: leave.s IL_017e // sequence point: <hidden> IL_0130: ldarg.0 IL_0131: ldnull IL_0132: stfld ""B Program.<M>d__1.<b>5__2"" // sequence point: node = node.Parent; IL_0137: ldarg.0 IL_0138: ldarg.0 IL_0139: ldfld ""Node Program.<M>d__1.node"" IL_013e: ldfld ""Node Node.Parent"" IL_0143: stfld ""Node Program.<M>d__1.node"" // sequence point: } IL_0148: nop IL_0149: ldarg.0 IL_014a: ldnull IL_014b: stfld ""A Program.<M>d__1.<a>5__1"" // sequence point: while (node != null) IL_0150: ldarg.0 IL_0151: ldfld ""Node Program.<M>d__1.node"" IL_0156: ldnull IL_0157: cgt.un IL_0159: stloc.s V_7 // sequence point: <hidden> IL_015b: ldloc.s V_7 IL_015d: brtrue IL_001f IL_0162: leave.s IL_017e } catch System.Exception { // sequence point: <hidden> IL_0164: stloc.s V_8 IL_0166: ldarg.0 IL_0167: ldc.i4.s -2 IL_0169: stfld ""int Program.<M>d__1.<>1__state"" IL_016e: ldarg.0 IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_0174: ldloc.s V_8 IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_017b: nop IL_017c: leave.s IL_0192 } // sequence point: } IL_017e: ldarg.0 IL_017f: ldc.i4.s -2 IL_0181: stfld ""int Program.<M>d__1.<>1__state"" // sequence point: <hidden> IL_0186: ldarg.0 IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0191: nop IL_0192: ret } ", sequencePoints: "Program+<M>d__1.MoveNext", source: source); } [Fact] [WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")] public void TestSequencePoints_28288() { var source = @" using System.Threading.Tasks; public class C { public static async Task Main() { object o = new C(); switch (o) { case C c: System.Console.Write(1); break; default: return; } if (M() != null) { } } private static object M() { return new C(); } }"; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 162 (0xa2) .maxstack 2 .locals init (int V_0, object V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: object o = new C(); IL_0008: ldarg.0 IL_0009: newobj ""C..ctor()"" IL_000e: stfld ""object C.<Main>d__0.<o>5__1"" // sequence point: switch (o) IL_0013: ldarg.0 IL_0014: ldarg.0 IL_0015: ldfld ""object C.<Main>d__0.<o>5__1"" IL_001a: stloc.1 // sequence point: <hidden> IL_001b: ldloc.1 IL_001c: stfld ""object C.<Main>d__0.<>s__3"" // sequence point: <hidden> IL_0021: ldarg.0 IL_0022: ldarg.0 IL_0023: ldfld ""object C.<Main>d__0.<>s__3"" IL_0028: isinst ""C"" IL_002d: stfld ""C C.<Main>d__0.<c>5__2"" IL_0032: ldarg.0 IL_0033: ldfld ""C C.<Main>d__0.<c>5__2"" IL_0038: brtrue.s IL_003c IL_003a: br.s IL_0047 // sequence point: <hidden> IL_003c: br.s IL_003e // sequence point: System.Console.Write(1); IL_003e: ldc.i4.1 IL_003f: call ""void System.Console.Write(int)"" IL_0044: nop // sequence point: break; IL_0045: br.s IL_0049 // sequence point: return; IL_0047: leave.s IL_0086 // sequence point: <hidden> IL_0049: ldarg.0 IL_004a: ldnull IL_004b: stfld ""C C.<Main>d__0.<c>5__2"" IL_0050: ldarg.0 IL_0051: ldnull IL_0052: stfld ""object C.<Main>d__0.<>s__3"" // sequence point: if (M() != null) IL_0057: call ""object C.M()"" IL_005c: ldnull IL_005d: cgt.un IL_005f: stloc.2 // sequence point: <hidden> IL_0060: ldloc.2 IL_0061: brfalse.s IL_0065 // sequence point: { IL_0063: nop // sequence point: } IL_0064: nop // sequence point: <hidden> IL_0065: leave.s IL_0086 } catch System.Exception { // sequence point: <hidden> IL_0067: stloc.3 IL_0068: ldarg.0 IL_0069: ldc.i4.s -2 IL_006b: stfld ""int C.<Main>d__0.<>1__state"" IL_0070: ldarg.0 IL_0071: ldnull IL_0072: stfld ""object C.<Main>d__0.<o>5__1"" IL_0077: ldarg.0 IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_007d: ldloc.3 IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0083: nop IL_0084: leave.s IL_00a1 } // sequence point: } IL_0086: ldarg.0 IL_0087: ldc.i4.s -2 IL_0089: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_008e: ldarg.0 IL_008f: ldnull IL_0090: stfld ""object C.<Main>d__0.<o>5__1"" IL_0095: ldarg.0 IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a0: nop IL_00a1: ret } ", sequencePoints: "C+<Main>d__0.MoveNext", source: source); } [Fact] public void SwitchExpressionWithPattern() { string source = WithWindowsLineBreaks(@" class C { static string M(object o) { return o switch { int i => $""Number: {i}"", _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""55"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0x37"" hidden=""true"" document=""1"" /> <entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3d""> <scope startOffset=""0x16"" endOffset=""0x2b""> <local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region DoStatement [Fact] public void DoStatement() { var source = WithWindowsLineBreaks( @"using System; public class SeqPointForWhile { public static void Main() { SeqPointForWhile obj = new SeqPointForWhile(); obj.While(234); } int field; public void While(int p) { do { p = (int)(p / 2); if (p > 100) { continue; } else if (p > 10) { field = 1; } else { break; } } while (p > 0); // SeqPt should be generated for [while (p > 0);] field = -1; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""SeqPointForWhile"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""28"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointForWhile"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""1"" offset=""71"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0xd"" hidden=""true"" document=""1"" /> <entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" /> <entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" /> <entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" /> <entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" /> <entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Constructor [WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")] [Fact] public void ConstructorSequencePoints1() { var source = WithWindowsLineBreaks( @"namespace NS { public class MyClass { int intTest; public MyClass() { intTest = 123; } public MyClass(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static int Main() { int intI = 1, intJ = 8; int intK = 3; // Can't step into Ctor MyClass mc = new MyClass(); // Can't step into Ctor mc = new MyClass(intI, intJ, intK); return mc.intTest - 12; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Dev10 vs. Roslyn // // Default Ctor (no param) // Dev10 Roslyn // ====================================================================================== // Code size 18 (0x12) // Code size 16 (0x10) // .maxstack 8 .maxstack 8 //* IL_0000: ldarg.0 *IL_0000: ldarg.0 // IL_0001: call IL_0001: callvirt // instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor() // IL_0006: nop *IL_0006: nop //* IL_0007: nop //* IL_0008: ldarg.0 *IL_0007: ldarg.0 // IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123 // IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest // IL_0010: nop //* IL_0011: ret *IL_000f: ret // ----------------------------------------------------------------------------------------- // SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""NS.MyClass"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> <method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values""> <customDebugInfo> <forward declaringType=""NS.MyClass"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" /> <entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> <method containingType=""NS.MyClass"" name=""Main""> <customDebugInfo> <forward declaringType=""NS.MyClass"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""29"" /> <slot kind=""0"" offset=""56"" /> <slot kind=""0"" offset=""126"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" /> <entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" /> <entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" /> <entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" /> <entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ConstructorSequencePoints2() { TestSequencePoints( @"using System; class D { public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class D { static D() [|{|] } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class D { [A] public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class D { [A] public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class C { } class D { [A] [|public D()|] { } }", TestOptions.DebugDll); } #endregion #region Destructor [Fact] public void Destructors() { var source = @" using System; public class Base { ~Base() { Console.WriteLine(); } } public class Derived : Base { ~Derived() { Console.WriteLine(); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Base"" name=""Finalize""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> </scope> </method> <method containingType=""Derived"" name=""Finalize""> <customDebugInfo> <forward declaringType=""Base"" methodName=""Finalize"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Field and Property Initializers [Fact] [WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")] public void TestPartialClassFieldInitializers() { var text1 = WithWindowsLineBreaks(@" public partial class C { int x = 1; } "); var text2 = WithWindowsLineBreaks(@" public partial class C { int y = 1; static void Main() { C c = new C(); } } "); // Having a unique name here may be important. The infrastructure of the pdb to xml conversion // loads the assembly into the ReflectionOnlyLoadFrom context. // So it's probably a good idea to have a new name for each assembly. var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") }); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" /> <file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" /> <file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] [WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")] public void TestPartialClassFieldInitializersWithLineDirectives() { var text1 = WithWindowsLineBreaks(@" using System; public partial class C { int x = 1; #line 12 ""foo.cs"" int z = Math.Abs(-3); int w = Math.Abs(4); #line 17 ""bar.cs"" double zed = Math.Sin(5); } #pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9"" "); var text2 = WithWindowsLineBreaks(@" using System; public partial class C { int y = 1; int x2 = 1; #line 12 ""foo2.cs"" int z2 = Math.Abs(-3); int w2 = Math.Abs(4); } "); var text3 = WithWindowsLineBreaks(@" using System; public partial class C { #line 112 ""mah.cs"" int y3 = 1; int x3 = 1; int z3 = Math.Abs(-3); #line default int w3 = Math.Abs(4); double zed3 = Math.Sin(5); C() { Console.WriteLine(""hi""); } static void Main() { C c = new C(); } } "); //Having a unique name here may be important. The infrastructure of the pdb to xml conversion //loads the assembly into the ReflectionOnlyLoadFrom context. //So it's probably a good idea to have a new name for each assembly. var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" /> <file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" /> <file id=""3"" name=""foo.cs"" language=""C#"" /> <file id=""4"" name=""bar.cs"" language=""C#"" /> <file id=""5"" name=""foo2.cs"" language=""C#"" /> <file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" /> <entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" /> <entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" /> <entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" /> <entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" /> <entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" /> <entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" /> <entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" /> <entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" /> <entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" /> <entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" /> <entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")] [Fact] public void TestFieldInitializerExpressionLambda() { var source = @" class C { int x = ((System.Func<int, int>)(z => z))(1); } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset=""-6"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__1_0"" parameterNames=""z""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FieldInitializerSequencePointSpans() { var source = @" class C { int x = 1, y = 2; } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Auto-Property [WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")] [Fact] public void BreakpointForAutoImplementedProperty() { var source = @" public class C { public static int AutoProp1 { get; private set; } internal string AutoProp2 { get; set; } internal protected C AutoProp3 { internal get; set; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_AutoProp1""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""get_AutoProp2""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""get_AutoProp3""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void PropertyDeclaration() { TestSequencePoints( @"using System; public class C { int P { [|get;|] set; } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get; [|set;|] } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get [|{|] return 0; } } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get; } = [|int.Parse(""42"")|]; }", TestOptions.DebugDll, TestOptions.Regular); } #endregion #region ReturnStatement [Fact] public void Return_Implicit() { var source = @"class C { static void Main() { } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Explicit() { var source = @"class C { static void Main() { return; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")] [Fact] public void RegressSeqPtEndOfMethodAfterReturn() { var source = WithWindowsLineBreaks( @"using System; public class SeqPointAfterReturn { public static int Main() { int ret = 0; ReturnVoid(100); if (field != ""Even"") ret = 1; ReturnVoid(99); if (field != ""Odd"") ret = ret + 1; string rets = ReturnValue(101); if (rets != ""Odd"") ret = ret + 1; rets = ReturnValue(102); if (rets != ""Even"") ret = ret + 1; return ret; } static string field; public static void ReturnVoid(int p) { int x = (int)(p % 2); if (x == 0) { field = ""Even""; } else { field = ""Odd""; } } public static string ReturnValue(int p) { int x = (int)(p % 2); if (x == 0) { return ""Even""; } else { return ""Odd""; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Expected are current actual output plus Two extra expected SeqPt: // <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> // <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" /> // // Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""SeqPointAfterReturn"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""204"" /> <slot kind=""1"" offset=""59"" /> <slot kind=""1"" offset=""138"" /> <slot kind=""1"" offset=""238"" /> <slot kind=""1"" offset=""330"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" /> <entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" /> <entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" /> <entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" /> <entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" /> <entry offset=""0x71"" hidden=""true"" document=""1"" /> <entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" /> <entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" /> <entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x81""> <namespace name=""System"" /> <local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" /> <local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""1"" offset=""42"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" /> <entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" /> <entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" /> <entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""1"" offset=""42"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" /> <entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" /> <entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" /> <entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region Exception Handling [WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")] [Fact] public void ExceptionHandling() { var source = WithWindowsLineBreaks(@" class Test { static int Main() { int ret = 0; // stop 1 try { // stop 2 throw new System.Exception(); // stop 3 } catch (System.Exception e) // stop 4 { // stop 5 ret = 1; // stop 6 } try { // stop 7 throw new System.Exception(); // stop 8 } catch // stop 9 { // stop 10 return ret; // stop 11 } } } "); // Dev12 inserts an additional sequence point on catch clause, just before // the exception object is assigned to the variable. We don't place that sequence point. // Also the scope of he exception variable is different. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Test.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""147"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" /> <entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" /> <entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" /> <entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <scope startOffset=""0xa"" endOffset=""0x11""> <local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug1() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class Test { static string filter(Exception e) { return null; } static void Main() { try { throw new InvalidOperationException(); } catch (IOException e) when (filter(e) != null) { Console.WriteLine(); } catch (Exception e) when (filter(e) != null) { Console.WriteLine(); } } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 89 (0x59) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { ~IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0023 IL_0014: stloc.0 -IL_0015: ldloc.0 IL_0016: call ""string Test.filter(System.Exception)"" IL_001b: ldnull IL_001c: cgt.un IL_001e: stloc.1 ~IL_001f: ldloc.1 IL_0020: ldc.i4.0 IL_0021: cgt.un IL_0023: endfilter } // end filter { // handler ~IL_0025: pop -IL_0026: nop -IL_0027: call ""void System.Console.WriteLine()"" IL_002c: nop -IL_002d: nop IL_002e: leave.s IL_0058 } filter { ~IL_0030: isinst ""System.Exception"" IL_0035: dup IL_0036: brtrue.s IL_003c IL_0038: pop IL_0039: ldc.i4.0 IL_003a: br.s IL_004b IL_003c: stloc.2 -IL_003d: ldloc.2 IL_003e: call ""string Test.filter(System.Exception)"" IL_0043: ldnull IL_0044: cgt.un IL_0046: stloc.3 ~IL_0047: ldloc.3 IL_0048: ldc.i4.0 IL_0049: cgt.un IL_004b: endfilter } // end filter { // handler ~IL_004d: pop -IL_004e: nop -IL_004f: call ""void System.Console.WriteLine()"" IL_0054: nop -IL_0055: nop IL_0056: leave.s IL_0058 } -IL_0058: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" /> <encLocalSlotMap> <slot kind=""0"" offset=""104"" /> <slot kind=""1"" offset=""120"" /> <slot kind=""0"" offset=""216"" /> <slot kind=""1"" offset=""230"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" /> <entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" /> <entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" /> <entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> <entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x59""> <scope startOffset=""0x8"" endOffset=""0x30""> <local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" /> </scope> <scope startOffset=""0x30"" endOffset=""0x58""> <local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug2() { var source = WithWindowsLineBreaks(@" class Test { static void Main() { try { throw new System.Exception(); } catch when (F()) { System.Console.WriteLine(); } } private static bool F() { return true; } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 2 .locals init (bool V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.Exception..ctor()"" IL_0007: throw } filter { ~IL_0008: pop -IL_0009: call ""bool Test.F()"" IL_000e: stloc.0 ~IL_000f: ldloc.0 IL_0010: ldc.i4.0 IL_0011: cgt.un IL_0013: endfilter } // end filter { // handler ~IL_0015: pop -IL_0016: nop -IL_0017: call ""void System.Console.WriteLine()"" IL_001c: nop -IL_001d: nop IL_001e: leave.s IL_0020 } -IL_0020: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""95"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug3() { var source = WithWindowsLineBreaks(@" class Test { static bool a = true; static void Main() { try { throw new System.Exception(); } catch when (a) { System.Console.WriteLine(); } } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 2 .locals init (bool V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.Exception..ctor()"" IL_0007: throw } filter { ~IL_0008: pop -IL_0009: ldsfld ""bool Test.a"" IL_000e: stloc.0 ~IL_000f: ldloc.0 IL_0010: ldc.i4.0 IL_0011: cgt.un IL_0013: endfilter } // end filter { // handler ~IL_0015: pop -IL_0016: nop -IL_0017: call ""void System.Console.WriteLine()"" IL_001c: nop -IL_001d: nop IL_001e: leave.s IL_0020 } -IL_0020: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""95"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" /> <entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Release3() { var source = @" class Test { static bool a = true; static void Main() { try { throw new System.Exception(); } catch when (a) { System.Console.WriteLine(); } } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll)); v.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .try { -IL_0000: newobj ""System.Exception..ctor()"" IL_0005: throw } filter { ~IL_0006: pop -IL_0007: ldsfld ""bool Test.a"" IL_000c: ldc.i4.0 IL_000d: cgt.un IL_000f: endfilter } // end filter { // handler ~IL_0011: pop -IL_0012: call ""void System.Console.WriteLine()"" -IL_0017: leave.s IL_0019 } -IL_0019: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" /> <entry offset=""0x6"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" /> <entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")] [Fact] public void BranchToStartOfTry() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string str = null; bool isEmpty = string.IsNullOrEmpty(str); // isEmpty is always true here, so it should never go thru this if statement. if (!isEmpty) { throw new Exception(); } try { Console.WriteLine(); } catch { } } } "); // Note the hidden sequence point @IL_0019. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""1"" offset=""177"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" /> <entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" /> <local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region UsingStatement [Fact] public void UsingStatement_EmbeddedStatement() { var source = WithWindowsLineBreaks(@" public class DisposableClass : System.IDisposable { public DisposableClass(int a) { } public void Dispose() { } } class C { static void Main() { using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2)) System.Console.WriteLine(""First""); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 53 (0x35) .maxstack 1 .locals init (DisposableClass V_0, //a DisposableClass V_1) //b // sequence point: { IL_0000: nop // sequence point: DisposableClass a = new DisposableClass(1) IL_0001: ldc.i4.1 IL_0002: newobj ""DisposableClass..ctor(int)"" IL_0007: stloc.0 .try { // sequence point: b = new DisposableClass(2) IL_0008: ldc.i4.2 IL_0009: newobj ""DisposableClass..ctor(int)"" IL_000e: stloc.1 .try { // sequence point: System.Console.WriteLine(""First""); IL_000f: ldstr ""First"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: nop IL_001a: leave.s IL_0027 } finally { // sequence point: <hidden> IL_001c: ldloc.1 IL_001d: brfalse.s IL_0026 IL_001f: ldloc.1 IL_0020: callvirt ""void System.IDisposable.Dispose()"" IL_0025: nop // sequence point: <hidden> IL_0026: endfinally } // sequence point: <hidden> IL_0027: leave.s IL_0034 } finally { // sequence point: <hidden> IL_0029: ldloc.0 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.0 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop // sequence point: <hidden> IL_0033: endfinally } // sequence point: } IL_0034: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" /> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" /> <entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" /> <entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <scope startOffset=""0x1"" endOffset=""0x34""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void UsingStatement_Block() { var source = WithWindowsLineBreaks(@" public class DisposableClass : System.IDisposable { public DisposableClass(int a) { } public void Dispose() { } } class C { static void Main() { using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4)) { System.Console.WriteLine(""Second""); } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 55 (0x37) .maxstack 1 .locals init (DisposableClass V_0, //c DisposableClass V_1) //d // sequence point: { IL_0000: nop // sequence point: DisposableClass c = new DisposableClass(3) IL_0001: ldc.i4.3 IL_0002: newobj ""DisposableClass..ctor(int)"" IL_0007: stloc.0 .try { // sequence point: d = new DisposableClass(4) IL_0008: ldc.i4.4 IL_0009: newobj ""DisposableClass..ctor(int)"" IL_000e: stloc.1 .try { // sequence point: { IL_000f: nop // sequence point: System.Console.WriteLine(""Second""); IL_0010: ldstr ""Second"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: nop // sequence point: } IL_001b: nop IL_001c: leave.s IL_0029 } finally { // sequence point: <hidden> IL_001e: ldloc.1 IL_001f: brfalse.s IL_0028 IL_0021: ldloc.1 IL_0022: callvirt ""void System.IDisposable.Dispose()"" IL_0027: nop // sequence point: <hidden> IL_0028: endfinally } // sequence point: <hidden> IL_0029: leave.s IL_0036 } finally { // sequence point: <hidden> IL_002b: ldloc.0 IL_002c: brfalse.s IL_0035 IL_002e: ldloc.0 IL_002f: callvirt ""void System.IDisposable.Dispose()"" IL_0034: nop // sequence point: <hidden> IL_0035: endfinally } // sequence point: } IL_0036: ret } " ); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" /> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" /> <entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" /> <entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" /> <entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" hidden=""true"" document=""1"" /> <entry offset=""0x28"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x37""> <scope startOffset=""0x1"" endOffset=""0x36""> <local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" /> <local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedConditional() { var source = @" class C { bool F() { bool x = true; bool value = false; using (var stream = new System.IO.MemoryStream()) if (x) { value = true; } else value = false; return value; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (bool V_0, //x bool V_1, //value System.IO.MemoryStream V_2, //stream bool V_3, bool V_4) // sequence point: { IL_0000: nop // sequence point: bool x = true; IL_0001: ldc.i4.1 IL_0002: stloc.0 // sequence point: bool value = false; IL_0003: ldc.i4.0 IL_0004: stloc.1 // sequence point: var stream = new System.IO.MemoryStream() IL_0005: newobj ""System.IO.MemoryStream..ctor()"" IL_000a: stloc.2 .try { // sequence point: if (x) IL_000b: ldloc.0 IL_000c: stloc.3 // sequence point: <hidden> IL_000d: ldloc.3 IL_000e: brfalse.s IL_0016 // sequence point: { IL_0010: nop // sequence point: value = true; IL_0011: ldc.i4.1 IL_0012: stloc.1 // sequence point: } IL_0013: nop // sequence point: <hidden> IL_0014: br.s IL_0018 // sequence point: value = false; IL_0016: ldc.i4.0 IL_0017: stloc.1 // sequence point: <hidden> IL_0018: leave.s IL_0025 } finally { // sequence point: <hidden> IL_001a: ldloc.2 IL_001b: brfalse.s IL_0024 IL_001d: ldloc.2 IL_001e: callvirt ""void System.IDisposable.Dispose()"" IL_0023: nop // sequence point: <hidden> IL_0024: endfinally } // sequence point: return value; IL_0025: ldloc.1 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a // sequence point: } IL_002a: ldloc.s V_4 IL_002c: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedConditional2() { var source = @" class C { bool F() { bool x = true; bool value = false; using (var stream = new System.IO.MemoryStream()) if (x) { value = true; } else { value = false; } return value; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 1 .locals init (bool V_0, //x bool V_1, //value System.IO.MemoryStream V_2, //stream bool V_3, bool V_4) // sequence point: { IL_0000: nop // sequence point: bool x = true; IL_0001: ldc.i4.1 IL_0002: stloc.0 // sequence point: bool value = false; IL_0003: ldc.i4.0 IL_0004: stloc.1 // sequence point: var stream = new System.IO.MemoryStream() IL_0005: newobj ""System.IO.MemoryStream..ctor()"" IL_000a: stloc.2 .try { // sequence point: if (x) IL_000b: ldloc.0 IL_000c: stloc.3 // sequence point: <hidden> IL_000d: ldloc.3 IL_000e: brfalse.s IL_0016 // sequence point: { IL_0010: nop // sequence point: value = true; IL_0011: ldc.i4.1 IL_0012: stloc.1 // sequence point: } IL_0013: nop // sequence point: <hidden> IL_0014: br.s IL_001a // sequence point: { IL_0016: nop // sequence point: value = false; IL_0017: ldc.i4.0 IL_0018: stloc.1 // sequence point: } IL_0019: nop // sequence point: <hidden> IL_001a: leave.s IL_0027 } finally { // sequence point: <hidden> IL_001c: ldloc.2 IL_001d: brfalse.s IL_0026 IL_001f: ldloc.2 IL_0020: callvirt ""void System.IDisposable.Dispose()"" IL_0025: nop // sequence point: <hidden> IL_0026: endfinally } // sequence point: return value; IL_0027: ldloc.1 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c // sequence point: } IL_002c: ldloc.s V_4 IL_002e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedWhile() { var source = @" class C { void F(bool x) { using (var stream = new System.IO.MemoryStream()) while (x) x = false; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //stream bool V_1) // sequence point: { IL_0000: nop // sequence point: var stream = new System.IO.MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: br.s IL_000c // sequence point: x = false; IL_0009: ldc.i4.0 IL_000a: starg.s V_1 // sequence point: while (x) IL_000c: ldarg.1 IL_000d: stloc.1 // sequence point: <hidden> IL_000e: ldloc.1 IL_000f: brtrue.s IL_0009 IL_0011: leave.s IL_001e } finally { // sequence point: <hidden> IL_0013: ldloc.0 IL_0014: brfalse.s IL_001d IL_0016: ldloc.0 IL_0017: callvirt ""void System.IDisposable.Dispose()"" IL_001c: nop // sequence point: <hidden> IL_001d: endfinally } // sequence point: } IL_001e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedFor() { var source = @" class C { void F(bool x) { using (var stream = new System.IO.MemoryStream()) for ( ; x == true; ) x = false; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //stream bool V_1) // sequence point: { IL_0000: nop // sequence point: var stream = new System.IO.MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: br.s IL_000c // sequence point: x = false; IL_0009: ldc.i4.0 IL_000a: starg.s V_1 // sequence point: x == true IL_000c: ldarg.1 IL_000d: stloc.1 // sequence point: <hidden> IL_000e: ldloc.1 IL_000f: brtrue.s IL_0009 IL_0011: leave.s IL_001e } finally { // sequence point: <hidden> IL_0013: ldloc.0 IL_0014: brfalse.s IL_001d IL_0016: ldloc.0 IL_0017: callvirt ""void System.IDisposable.Dispose()"" IL_001c: nop // sequence point: <hidden> IL_001d: endfinally } // sequence point: } IL_001e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void LockStatement_EmbeddedIf() { var source = @" class C { void F(bool x) { string y = """"; lock (y) if (!x) System.Console.Write(1); else System.Console.Write(2); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, //y string V_1, bool V_2, bool V_3) // sequence point: { IL_0000: nop // sequence point: string y = """"; IL_0001: ldstr """" IL_0006: stloc.0 // sequence point: lock (y) IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldc.i4.0 IL_000a: stloc.2 .try { IL_000b: ldloc.1 IL_000c: ldloca.s V_2 IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0013: nop // sequence point: if (!x) IL_0014: ldarg.1 IL_0015: ldc.i4.0 IL_0016: ceq IL_0018: stloc.3 // sequence point: <hidden> IL_0019: ldloc.3 IL_001a: brfalse.s IL_0025 // sequence point: System.Console.Write(1); IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.Write(int)"" IL_0022: nop // sequence point: <hidden> IL_0023: br.s IL_002c // sequence point: System.Console.Write(2); IL_0025: ldc.i4.2 IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop // sequence point: <hidden> IL_002c: leave.s IL_0039 } finally { // sequence point: <hidden> IL_002e: ldloc.2 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.1 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop // sequence point: <hidden> IL_0038: endfinally } // sequence point: } IL_0039: ret } ", sequencePoints: "C.F", source: source); } #endregion #region Using Declaration [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_BodyBlockScope() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { static void Main() { using MemoryStream m = new MemoryStream(), n = new MemoryStream(); Console.WriteLine(1); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // Duplicate sequence point at `}` v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 45 (0x2d) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //m System.IO.MemoryStream V_1) //n // sequence point: { IL_0000: nop // sequence point: using MemoryStream m = new MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: n = new MemoryStream() IL_0007: newobj ""System.IO.MemoryStream..ctor()"" IL_000c: stloc.1 .try { // sequence point: Console.WriteLine(1); IL_000d: ldc.i4.1 IL_000e: call ""void System.Console.WriteLine(int)"" IL_0013: nop // sequence point: } IL_0014: leave.s IL_002c } finally { // sequence point: <hidden> IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.1 IL_001a: callvirt ""void System.IDisposable.Dispose()"" IL_001f: nop // sequence point: <hidden> IL_0020: endfinally } } finally { // sequence point: <hidden> IL_0021: ldloc.0 IL_0022: brfalse.s IL_002b IL_0024: ldloc.0 IL_0025: callvirt ""void System.IDisposable.Dispose()"" IL_002a: nop // sequence point: <hidden> IL_002b: endfinally } // sequence point: } IL_002c: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""30"" /> <slot kind=""0"" offset=""54"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2d""> <namespace name=""System"" /> <namespace name=""System.IO"" /> <local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> <local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_BodyBlockScopeWithReturn() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { static int Main() { using MemoryStream m = new MemoryStream(); Console.WriteLine(1); return 1; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // Duplicate sequence point at `}` v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //m int V_1) // sequence point: { IL_0000: nop // sequence point: using MemoryStream m = new MemoryStream(); IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: Console.WriteLine(1); IL_0007: ldc.i4.1 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop // sequence point: return 1; IL_000e: ldc.i4.1 IL_000f: stloc.1 IL_0010: leave.s IL_001d } finally { // sequence point: <hidden> IL_0012: ldloc.0 IL_0013: brfalse.s IL_001c IL_0015: ldloc.0 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop // sequence point: <hidden> IL_001c: endfinally } // sequence point: } IL_001d: ldloc.1 IL_001e: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""30"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <namespace name=""System"" /> <namespace name=""System.IO"" /> <local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_IfBodyScope() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { public static bool G() => true; static void Main() { if (G()) { using var m = new MemoryStream(); Console.WriteLine(1); } Console.WriteLine(2); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // In this case the sequence point `}` is not emitted on the leave instruction, // but to a nop instruction following the disposal. v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 46 (0x2e) .maxstack 1 .locals init (bool V_0, System.IO.MemoryStream V_1) //m // sequence point: { IL_0000: nop // sequence point: if (G()) IL_0001: call ""bool C.G()"" IL_0006: stloc.0 // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0026 // sequence point: { IL_000a: nop // sequence point: using var m = new MemoryStream(); IL_000b: newobj ""System.IO.MemoryStream..ctor()"" IL_0010: stloc.1 .try { // sequence point: Console.WriteLine(1); IL_0011: ldc.i4.1 IL_0012: call ""void System.Console.WriteLine(int)"" IL_0017: nop IL_0018: leave.s IL_0025 } finally { // sequence point: <hidden> IL_001a: ldloc.1 IL_001b: brfalse.s IL_0024 IL_001d: ldloc.1 IL_001e: callvirt ""void System.IDisposable.Dispose()"" IL_0023: nop // sequence point: <hidden> IL_0024: endfinally } // sequence point: } IL_0025: nop // sequence point: Console.WriteLine(2); IL_0026: ldc.i4.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop // sequence point: } IL_002d: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""55"" /> </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=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" /> <entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2e""> <scope startOffset=""0xa"" endOffset=""0x26""> <local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion // LockStatement tested in CodeGenLock #region Anonymous Type [Fact] public void AnonymousType_Empty() { var source = WithWindowsLineBreaks(@" class Program { static void Main(string[] args) { var o = new {}; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void AnonymousType_NonEmpty() { var source = WithWindowsLineBreaks(@" class Program { static void Main(string[] args) { var o = new { a = 1 }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""31"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region FixedStatement [Fact] public void FixedStatementSingleAddress() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int x; static void Main() { C c = new C(); fixed (int* p = &c.x) { *p = 1; } Console.WriteLine(c.x); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""47"" /> <slot kind=""9"" offset=""47"" /> </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=""23"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" /> <entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" /> <entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x26""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x19""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementSingleString() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { static void Main() { fixed (char* p = ""hello"") { Console.WriteLine(*p); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""24"" /> <slot kind=""9"" offset=""24"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x21""> <local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementSingleArray() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int[] a = new int[1]; static void Main() { C c = new C(); Console.Write(c.a[0]); fixed (int* p = c.a) { (*p)++; } Console.Write(c.a[0]); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""temp"" /> </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=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" /> <entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" /> <entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" /> <entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x15"" endOffset=""0x3c""> <local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleAddresses() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int x; int y; static void Main() { C c = new C(); fixed (int* p = &c.x, q = &c.y) { *p = 1; *q = 2; } Console.WriteLine(c.x + c.y); } } "); // NOTE: stop on each declarator. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""47"" /> <slot kind=""0"" offset=""57"" /> <slot kind=""9"" offset=""47"" /> <slot kind=""9"" offset=""57"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" /> <entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" /> <entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" /> <entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" /> <entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x2c""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleStrings() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { static void Main() { fixed (char* p = ""hello"", q = ""goodbye"") { Console.Write(*p); Console.Write(*q); } } } "); // NOTE: stop on each declarator. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""24"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""9"" offset=""24"" /> <slot kind=""9"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" /> <entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x3f""> <local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" /> <local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleArrays() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int[] a = new int[1]; int[] b = new int[1]; static void Main() { C c = new C(); Console.Write(c.a[0]); Console.Write(c.b[0]); fixed (int* p = c.a, q = c.b) { *p = 1; *q = 2; } Console.Write(c.a[0]); Console.Write(c.b[0]); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""111"" /> <slot kind=""0"" offset=""120"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" /> <entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" /> <entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" /> <entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" /> <entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" /> <entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" /> <entry offset=""0x68"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" /> <entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" /> <entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8a""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" /> <scope startOffset=""0x23"" endOffset=""0x6d""> <local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleMixed() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (char* p = &c.c, q = c.a, r = ""hello"") { Console.Write((int)*p); Console.Write((int)*q); Console.Write((int)*r); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""48"" /> <slot kind=""0"" offset=""58"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""9"" offset=""48"" /> <slot kind=""temp"" /> <slot kind=""9"" offset=""67"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" /> <entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" /> <entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" /> <entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6e""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x6d""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> <local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Line Directives [Fact] public void LineDirective() { var source = @" #line 50 ""foo.cs"" using System; unsafe class C { static void Main() { Console.Write(1); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""foo.cs"" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" /> <entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledLineDirective() { var source = @" #if false #line 50 ""foo.cs"" #endif using System; unsafe class C { static void Main() { Console.Write(1); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestLineDirectivesHidden() { var text1 = WithWindowsLineBreaks(@" using System; public class C { public void Foo() { foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } #line hidden foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } #line default foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } } } "); var compilation = CreateCompilation(text1, options: TestOptions.DebugDll); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Foo""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""6"" offset=""137"" /> <slot kind=""8"" offset=""137"" /> <slot kind=""0"" offset=""137"" /> <slot kind=""6"" offset=""264"" /> <slot kind=""8"" offset=""264"" /> <slot kind=""0"" offset=""264"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" /> <entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" /> <entry offset=""0x2f"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" /> <entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" /> <entry offset=""0x7b"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" /> <entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" /> <entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" /> <entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" hidden=""true"" document=""1"" /> <entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9d""> <namespace name=""System"" /> <scope startOffset=""0x18"" endOffset=""0x25""> <local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" /> </scope> <scope startOffset=""0x47"" endOffset=""0x57""> <local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" /> </scope> <scope startOffset=""0x7d"" endOffset=""0x8e""> <local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void HiddenMethods() { var src = @" using System; class C { #line hidden public static void H() { F(); } #line default public static void G() { F(); } #line hidden public static void F() { { const int z = 1; var (x, y) = (1,2); Console.WriteLine(x + z); } { dynamic x = 1; Console.WriteLine(x); } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" /> <entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void HiddenEntryPoint() { var src = @" class C { #line hidden public static void Main() { } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe); // Note: Dev10 emitted a hidden sequence point to #line hidden method, // which enabled the debugger to locate the first user visible sequence point starting from the entry point. // Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of // #line hidden directive. c.VerifyPdb(@" <symbols> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main"" format=""windows""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> </method> </methods> </symbols>", // When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method // and thus there is no entry point record either. options: PdbValidationOptions.SkipConversionValidation); } [Fact] public void HiddenIterator() { var src = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class C { public static void Main() { F(); } #line hidden public static IEnumerable<int> F() { { const int z = 1; var (x, y) = (1,2); Console.WriteLine(x + z); } { dynamic x = 1; Console.WriteLine(x); } yield return 1; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll); // We don't really need the debug info for kickoff method when the entire iterator method is hidden, // but it doesn't hurt and removing it would need extra effort that's unnecessary. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""C"" name=""F""> <customDebugInfo> <forwardIterator name=""&lt;F&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""61"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""158"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); } #endregion #region Nested Types [Fact] public void NestedTypes() { string source = WithWindowsLineBreaks(@" using System; namespace N { public class C { public class D<T> { public class E { public static void f(int a) { Console.WriteLine(); } } } } } "); var c = CreateCompilation(Parse(source, filename: "file.cs")); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" /> </files> <methods> <method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""0"" /> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" /> <entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } #endregion #region Expression Bodied Members [Fact] public void ExpressionBodiedProperty() { var source = WithWindowsLineBreaks(@" class C { public int P => M(); public int M() { return 2; } }"); var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_P"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public int this[Int32 i] => M(); public int M() { return 2; } }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedMethod() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Int32 P => 2; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedOperator() { var comp = CreateCompilationWithMscorlib45(@" class C { public static C operator ++(C c) => c; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""op_Increment"" parameterNames=""c""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedConversion() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public static explicit operator C(Int32 i) => new C(); }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""op_Explicit"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedConstructor() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public int X; public C(Int32 x) => X = x; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedDestructor() { var comp = CreateCompilationWithMscorlib45(@" class C { public int X; ~C() => X = 0; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Finalize""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedAccessor() { var comp = CreateCompilationWithMscorlib45(@" class C { public int x; public int X { get => x; set => x = value; } public event System.Action E { add => x = 1; remove => x = 0; } }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_X""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_X"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""add_E"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""remove_E"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Synthesized Methods [Fact] public void ImportsInLambda() { var source = WithWindowsLineBreaks( @"using System.Collections.Generic; using System.Linq; class C { static void M() { System.Action f = () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; f(); } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<>c.<M>b__0_0", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> <encLocalSlotMap> <slot kind=""0"" offset=""63"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""30"" document=""1"" /> <entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3a""> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ImportsInIterator() { var source = WithWindowsLineBreaks( @"using System.Collections.Generic; using System.Linq; class C { static IEnumerable<object> F() { var c = new[] { 1, 2, 3 }; foreach (var i in c.Select(i => i)) { yield return i; } } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<F>d__0.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c"" methodName=""&lt;F&gt;b__0_0"" parameterNames=""i"" /> <hoistedLocalScopes> <slot startOffset=""0x27"" endOffset=""0xd5"" /> <slot /> <slot startOffset=""0x7f"" endOffset=""0xb6"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" /> <entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" /> <entry offset=""0x7d"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" /> <entry offset=""0xad"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0xd5"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ImportsInAsync() { var source = WithWindowsLineBreaks( @"using System.Linq; using System.Threading.Tasks; class C { static async Task F() { var c = new[] { 1, 2, 3 }; c.Select(i => i); } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<F>d__0.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c"" methodName=""&lt;F&gt;b__0_0"" parameterNames=""i"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x87"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" /> <entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0x4c"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x73"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""F"" /> </asyncInfo> </method> </methods> </symbols>"); } [WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")] [Fact] public void ImportsInAsyncLambda() { var source = WithWindowsLineBreaks( @"using System.Linq; class C { static void M() { System.Action f = async () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<>c.<M>b__0_0", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forwardIterator name=""&lt;&lt;M&gt;b__0_0&gt;d"" /> <encLocalSlotMap> <slot kind=""0"" offset=""69"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c+&lt;&lt;M&gt;b__0_0&gt;d"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x87"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""50"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" /> <entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x4c"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0x4c"" /> <kickoffMethod declaringType=""C+&lt;&gt;c"" methodName=""&lt;M&gt;b__0_0"" /> </asyncInfo> </method> </methods> </symbols>"); } #endregion #region Patterns [Fact] public void SyntaxOffset_IsPattern() { var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2d""> <local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchStatement() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static int Main() { switch (F()) { // declaration pattern case int x when G(x) > 10: return 1; // discard pattern case bool _: return 2; // var pattern case var (y, z): return 3; // constant pattern case 4.0: return 4; // positional patterns case C() when B(): return 5; case (): return 6; case C(int p, C(int q)): return 7; case C(x: int p): return 8; // property pattern case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9; default: return 10; }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @" { // Code size 432 (0x1b0) .maxstack 3 .locals init (int V_0, //x object V_1, //y object V_2, //z int V_3, //p int V_4, //q int V_5, //p int V_6, //z object V_7, System.Runtime.CompilerServices.ITuple V_8, int V_9, double V_10, C V_11, object V_12, C V_13, D V_14, int V_15, D V_16, int V_17, C V_18, object V_19, int V_20) // sequence point: { IL_0000: nop // sequence point: switch (F()) IL_0001: call ""object Program.F()"" IL_0006: stloc.s V_19 // sequence point: <hidden> IL_0008: ldloc.s V_19 IL_000a: stloc.s V_7 // sequence point: <hidden> IL_000c: ldloc.s V_7 IL_000e: isinst ""int"" IL_0013: brfalse.s IL_0022 IL_0015: ldloc.s V_7 IL_0017: unbox.any ""int"" IL_001c: stloc.0 // sequence point: <hidden> IL_001d: br IL_014d IL_0022: ldloc.s V_7 IL_0024: isinst ""bool"" IL_0029: brtrue IL_015e IL_002e: ldloc.s V_7 IL_0030: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0035: stloc.s V_8 IL_0037: ldloc.s V_8 IL_0039: brfalse.s IL_0080 IL_003b: ldloc.s V_8 IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0042: stloc.s V_9 // sequence point: <hidden> IL_0044: ldloc.s V_9 IL_0046: ldc.i4.2 IL_0047: bne.un.s IL_0060 IL_0049: ldloc.s V_8 IL_004b: ldc.i4.0 IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0051: stloc.1 // sequence point: <hidden> IL_0052: ldloc.s V_8 IL_0054: ldc.i4.1 IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_005a: stloc.2 // sequence point: <hidden> IL_005b: br IL_0163 IL_0060: ldloc.s V_7 IL_0062: isinst ""C"" IL_0067: brtrue IL_016f IL_006c: br.s IL_0077 IL_006e: ldloc.s V_9 IL_0070: brfalse IL_018c IL_0075: br.s IL_00b5 IL_0077: ldloc.s V_9 IL_0079: brfalse IL_018c IL_007e: br.s IL_00f5 IL_0080: ldloc.s V_7 IL_0082: isinst ""double"" IL_0087: brfalse.s IL_00a7 IL_0089: ldloc.s V_7 IL_008b: unbox.any ""double"" IL_0090: stloc.s V_10 // sequence point: <hidden> IL_0092: ldloc.s V_10 IL_0094: ldc.r8 4 IL_009d: beq IL_016a IL_00a2: br IL_01a7 IL_00a7: ldloc.s V_7 IL_00a9: isinst ""C"" IL_00ae: brtrue IL_017b IL_00b3: br.s IL_00f5 IL_00b5: ldloc.s V_7 IL_00b7: castclass ""C"" IL_00bc: stloc.s V_11 // sequence point: <hidden> IL_00be: ldloc.s V_11 IL_00c0: ldloca.s V_3 IL_00c2: ldloca.s V_12 IL_00c4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00c9: nop // sequence point: <hidden> IL_00ca: ldloc.s V_12 IL_00cc: isinst ""C"" IL_00d1: stloc.s V_13 IL_00d3: ldloc.s V_13 IL_00d5: brfalse.s IL_00e6 IL_00d7: ldloc.s V_13 IL_00d9: ldloca.s V_4 IL_00db: callvirt ""void C.Deconstruct(out int)"" IL_00e0: nop // sequence point: <hidden> IL_00e1: br IL_0191 IL_00e6: ldloc.s V_11 IL_00e8: ldloca.s V_5 IL_00ea: callvirt ""void C.Deconstruct(out int)"" IL_00ef: nop // sequence point: <hidden> IL_00f0: br IL_0198 IL_00f5: ldloc.s V_7 IL_00f7: isinst ""D"" IL_00fc: stloc.s V_14 IL_00fe: ldloc.s V_14 IL_0100: brfalse IL_01a7 IL_0105: ldloc.s V_14 IL_0107: callvirt ""int D.P.get"" IL_010c: stloc.s V_15 // sequence point: <hidden> IL_010e: ldloc.s V_15 IL_0110: ldc.i4.1 IL_0111: bne.un IL_01a7 IL_0116: ldloc.s V_14 IL_0118: callvirt ""D D.Q.get"" IL_011d: stloc.s V_16 // sequence point: <hidden> IL_011f: ldloc.s V_16 IL_0121: brfalse IL_01a7 IL_0126: ldloc.s V_16 IL_0128: callvirt ""int D.P.get"" IL_012d: stloc.s V_17 // sequence point: <hidden> IL_012f: ldloc.s V_17 IL_0131: ldc.i4.2 IL_0132: bne.un.s IL_01a7 IL_0134: ldloc.s V_14 IL_0136: callvirt ""C D.R.get"" IL_013b: stloc.s V_18 // sequence point: <hidden> IL_013d: ldloc.s V_18 IL_013f: brfalse.s IL_01a7 IL_0141: ldloc.s V_18 IL_0143: ldloca.s V_6 IL_0145: callvirt ""void C.Deconstruct(out int)"" IL_014a: nop // sequence point: <hidden> IL_014b: br.s IL_019f // sequence point: when G(x) > 10 IL_014d: ldloc.0 IL_014e: call ""int Program.G(int)"" IL_0153: ldc.i4.s 10 IL_0155: bgt.s IL_0159 // sequence point: <hidden> IL_0157: br.s IL_01a7 // sequence point: return 1; IL_0159: ldc.i4.1 IL_015a: stloc.s V_20 IL_015c: br.s IL_01ad // sequence point: return 2; IL_015e: ldc.i4.2 IL_015f: stloc.s V_20 IL_0161: br.s IL_01ad // sequence point: <hidden> IL_0163: br.s IL_0165 // sequence point: return 3; IL_0165: ldc.i4.3 IL_0166: stloc.s V_20 IL_0168: br.s IL_01ad // sequence point: return 4; IL_016a: ldc.i4.4 IL_016b: stloc.s V_20 IL_016d: br.s IL_01ad // sequence point: when B() IL_016f: call ""bool Program.B()"" IL_0174: brtrue.s IL_0187 // sequence point: <hidden> IL_0176: br IL_006e // sequence point: when B() IL_017b: call ""bool Program.B()"" IL_0180: brtrue.s IL_0187 // sequence point: <hidden> IL_0182: br IL_00b5 // sequence point: return 5; IL_0187: ldc.i4.5 IL_0188: stloc.s V_20 IL_018a: br.s IL_01ad // sequence point: return 6; IL_018c: ldc.i4.6 IL_018d: stloc.s V_20 IL_018f: br.s IL_01ad // sequence point: <hidden> IL_0191: br.s IL_0193 // sequence point: return 7; IL_0193: ldc.i4.7 IL_0194: stloc.s V_20 IL_0196: br.s IL_01ad // sequence point: <hidden> IL_0198: br.s IL_019a // sequence point: return 8; IL_019a: ldc.i4.8 IL_019b: stloc.s V_20 IL_019d: br.s IL_01ad // sequence point: <hidden> IL_019f: br.s IL_01a1 // sequence point: return 9; IL_01a1: ldc.i4.s 9 IL_01a3: stloc.s V_20 IL_01a5: br.s IL_01ad // sequence point: return 10; IL_01a7: ldc.i4.s 10 IL_01a9: stloc.s V_20 IL_01ab: br.s IL_01ad // sequence point: } IL_01ad: ldloc.s V_20 IL_01af: ret } ", source: source); verifier.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""93"" /> <slot kind=""0"" offset=""244"" /> <slot kind=""0"" offset=""247"" /> <slot kind=""0"" offset=""465"" /> <slot kind=""0"" offset=""474"" /> <slot kind=""0"" offset=""516"" /> <slot kind=""0"" offset=""617"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""35"" offset=""11"" ordinal=""2"" /> <slot kind=""35"" offset=""11"" ordinal=""3"" /> <slot kind=""35"" offset=""11"" ordinal=""4"" /> <slot kind=""35"" offset=""11"" ordinal=""5"" /> <slot kind=""35"" offset=""11"" ordinal=""6"" /> <slot kind=""35"" offset=""11"" ordinal=""7"" /> <slot kind=""35"" offset=""11"" ordinal=""8"" /> <slot kind=""35"" offset=""11"" ordinal=""9"" /> <slot kind=""35"" offset=""11"" ordinal=""10"" /> <slot kind=""35"" offset=""11"" ordinal=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> <entry offset=""0x52"" hidden=""true"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" hidden=""true"" document=""1"" /> <entry offset=""0xf0"" hidden=""true"" document=""1"" /> <entry offset=""0x10e"" hidden=""true"" document=""1"" /> <entry offset=""0x11f"" hidden=""true"" document=""1"" /> <entry offset=""0x12f"" hidden=""true"" document=""1"" /> <entry offset=""0x13d"" hidden=""true"" document=""1"" /> <entry offset=""0x14b"" hidden=""true"" document=""1"" /> <entry offset=""0x14d"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" /> <entry offset=""0x15e"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" /> <entry offset=""0x163"" hidden=""true"" document=""1"" /> <entry offset=""0x165"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" /> <entry offset=""0x16a"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" /> <entry offset=""0x16f"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x176"" hidden=""true"" document=""1"" /> <entry offset=""0x17b"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x182"" hidden=""true"" document=""1"" /> <entry offset=""0x187"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" /> <entry offset=""0x18c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" /> <entry offset=""0x191"" hidden=""true"" document=""1"" /> <entry offset=""0x193"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19a"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" /> <entry offset=""0x19f"" hidden=""true"" document=""1"" /> <entry offset=""0x1a1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" /> <entry offset=""0x1a7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" /> <entry offset=""0x1ad"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b0""> <scope startOffset=""0x14d"" endOffset=""0x15e""> <local name=""x"" il_index=""0"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" /> </scope> <scope startOffset=""0x163"" endOffset=""0x16a""> <local name=""y"" il_index=""1"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> <local name=""z"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> </scope> <scope startOffset=""0x191"" endOffset=""0x198""> <local name=""p"" il_index=""3"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> <local name=""q"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> </scope> <scope startOffset=""0x198"" endOffset=""0x19f""> <local name=""p"" il_index=""5"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" /> </scope> <scope startOffset=""0x19f"" endOffset=""0x1a7""> <local name=""z"" il_index=""6"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchExpression() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static void Main() { var a = F() switch { // declaration pattern int x when G(x) > 10 => 1, // discard pattern bool _ => 2, // var pattern var (y, z) => 3, // constant pattern 4.0 => 4, // positional patterns C() when B() => 5, () => 6, C(int p, C(int q)) => 7, C(x: int p) => 8, // property pattern D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9, _ => 10, }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); // note no sequence points emitted within the switch expression verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @" { // Code size 437 (0x1b5) .maxstack 3 .locals init (int V_0, //a int V_1, //x object V_2, //y object V_3, //z int V_4, //p int V_5, //q int V_6, //p int V_7, //z int V_8, object V_9, System.Runtime.CompilerServices.ITuple V_10, int V_11, double V_12, C V_13, object V_14, C V_15, D V_16, int V_17, D V_18, int V_19, C V_20) -IL_0000: nop -IL_0001: call ""object Program.F()"" IL_0006: stloc.s V_9 IL_0008: ldc.i4.1 IL_0009: brtrue.s IL_000c -IL_000b: nop ~IL_000c: ldloc.s V_9 IL_000e: isinst ""int"" IL_0013: brfalse.s IL_0022 IL_0015: ldloc.s V_9 IL_0017: unbox.any ""int"" IL_001c: stloc.1 ~IL_001d: br IL_014d IL_0022: ldloc.s V_9 IL_0024: isinst ""bool"" IL_0029: brtrue IL_015e IL_002e: ldloc.s V_9 IL_0030: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0035: stloc.s V_10 IL_0037: ldloc.s V_10 IL_0039: brfalse.s IL_0080 IL_003b: ldloc.s V_10 IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0042: stloc.s V_11 ~IL_0044: ldloc.s V_11 IL_0046: ldc.i4.2 IL_0047: bne.un.s IL_0060 IL_0049: ldloc.s V_10 IL_004b: ldc.i4.0 IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0051: stloc.2 ~IL_0052: ldloc.s V_10 IL_0054: ldc.i4.1 IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_005a: stloc.3 ~IL_005b: br IL_0163 IL_0060: ldloc.s V_9 IL_0062: isinst ""C"" IL_0067: brtrue IL_016f IL_006c: br.s IL_0077 IL_006e: ldloc.s V_11 IL_0070: brfalse IL_018c IL_0075: br.s IL_00b5 IL_0077: ldloc.s V_11 IL_0079: brfalse IL_018c IL_007e: br.s IL_00f5 IL_0080: ldloc.s V_9 IL_0082: isinst ""double"" IL_0087: brfalse.s IL_00a7 IL_0089: ldloc.s V_9 IL_008b: unbox.any ""double"" IL_0090: stloc.s V_12 ~IL_0092: ldloc.s V_12 IL_0094: ldc.r8 4 IL_009d: beq IL_016a IL_00a2: br IL_01a7 IL_00a7: ldloc.s V_9 IL_00a9: isinst ""C"" IL_00ae: brtrue IL_017b IL_00b3: br.s IL_00f5 IL_00b5: ldloc.s V_9 IL_00b7: castclass ""C"" IL_00bc: stloc.s V_13 ~IL_00be: ldloc.s V_13 IL_00c0: ldloca.s V_4 IL_00c2: ldloca.s V_14 IL_00c4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00c9: nop ~IL_00ca: ldloc.s V_14 IL_00cc: isinst ""C"" IL_00d1: stloc.s V_15 IL_00d3: ldloc.s V_15 IL_00d5: brfalse.s IL_00e6 IL_00d7: ldloc.s V_15 IL_00d9: ldloca.s V_5 IL_00db: callvirt ""void C.Deconstruct(out int)"" IL_00e0: nop ~IL_00e1: br IL_0191 IL_00e6: ldloc.s V_13 IL_00e8: ldloca.s V_6 IL_00ea: callvirt ""void C.Deconstruct(out int)"" IL_00ef: nop ~IL_00f0: br IL_0198 IL_00f5: ldloc.s V_9 IL_00f7: isinst ""D"" IL_00fc: stloc.s V_16 IL_00fe: ldloc.s V_16 IL_0100: brfalse IL_01a7 IL_0105: ldloc.s V_16 IL_0107: callvirt ""int D.P.get"" IL_010c: stloc.s V_17 ~IL_010e: ldloc.s V_17 IL_0110: ldc.i4.1 IL_0111: bne.un IL_01a7 IL_0116: ldloc.s V_16 IL_0118: callvirt ""D D.Q.get"" IL_011d: stloc.s V_18 ~IL_011f: ldloc.s V_18 IL_0121: brfalse IL_01a7 IL_0126: ldloc.s V_18 IL_0128: callvirt ""int D.P.get"" IL_012d: stloc.s V_19 ~IL_012f: ldloc.s V_19 IL_0131: ldc.i4.2 IL_0132: bne.un.s IL_01a7 IL_0134: ldloc.s V_16 IL_0136: callvirt ""C D.R.get"" IL_013b: stloc.s V_20 ~IL_013d: ldloc.s V_20 IL_013f: brfalse.s IL_01a7 IL_0141: ldloc.s V_20 IL_0143: ldloca.s V_7 IL_0145: callvirt ""void C.Deconstruct(out int)"" IL_014a: nop ~IL_014b: br.s IL_019f -IL_014d: ldloc.1 IL_014e: call ""int Program.G(int)"" IL_0153: ldc.i4.s 10 IL_0155: bgt.s IL_0159 ~IL_0157: br.s IL_01a7 -IL_0159: ldc.i4.1 IL_015a: stloc.s V_8 IL_015c: br.s IL_01ad -IL_015e: ldc.i4.2 IL_015f: stloc.s V_8 IL_0161: br.s IL_01ad ~IL_0163: br.s IL_0165 -IL_0165: ldc.i4.3 IL_0166: stloc.s V_8 IL_0168: br.s IL_01ad -IL_016a: ldc.i4.4 IL_016b: stloc.s V_8 IL_016d: br.s IL_01ad -IL_016f: call ""bool Program.B()"" IL_0174: brtrue.s IL_0187 ~IL_0176: br IL_006e -IL_017b: call ""bool Program.B()"" IL_0180: brtrue.s IL_0187 ~IL_0182: br IL_00b5 -IL_0187: ldc.i4.5 IL_0188: stloc.s V_8 IL_018a: br.s IL_01ad -IL_018c: ldc.i4.6 IL_018d: stloc.s V_8 IL_018f: br.s IL_01ad ~IL_0191: br.s IL_0193 -IL_0193: ldc.i4.7 IL_0194: stloc.s V_8 IL_0196: br.s IL_01ad ~IL_0198: br.s IL_019a -IL_019a: ldc.i4.8 IL_019b: stloc.s V_8 IL_019d: br.s IL_01ad ~IL_019f: br.s IL_01a1 -IL_01a1: ldc.i4.s 9 IL_01a3: stloc.s V_8 IL_01a5: br.s IL_01ad -IL_01a7: ldc.i4.s 10 IL_01a9: stloc.s V_8 IL_01ab: br.s IL_01ad ~IL_01ad: ldc.i4.1 IL_01ae: brtrue.s IL_01b1 -IL_01b0: nop ~IL_01b1: ldloc.s V_8 IL_01b3: stloc.0 -IL_01b4: ret } "); verifier.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""94"" /> <slot kind=""0"" offset=""225"" /> <slot kind=""0"" offset=""228"" /> <slot kind=""0"" offset=""406"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""447"" /> <slot kind=""0"" offset=""539"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""23"" /> <slot kind=""35"" offset=""23"" ordinal=""1"" /> <slot kind=""35"" offset=""23"" ordinal=""2"" /> <slot kind=""35"" offset=""23"" ordinal=""3"" /> <slot kind=""35"" offset=""23"" ordinal=""4"" /> <slot kind=""35"" offset=""23"" ordinal=""5"" /> <slot kind=""35"" offset=""23"" ordinal=""6"" /> <slot kind=""35"" offset=""23"" ordinal=""7"" /> <slot kind=""35"" offset=""23"" ordinal=""8"" /> <slot kind=""35"" offset=""23"" ordinal=""9"" /> <slot kind=""35"" offset=""23"" ordinal=""10"" /> <slot kind=""35"" offset=""23"" ordinal=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" /> <entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> <entry offset=""0x52"" hidden=""true"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" hidden=""true"" document=""1"" /> <entry offset=""0xf0"" hidden=""true"" document=""1"" /> <entry offset=""0x10e"" hidden=""true"" document=""1"" /> <entry offset=""0x11f"" hidden=""true"" document=""1"" /> <entry offset=""0x12f"" hidden=""true"" document=""1"" /> <entry offset=""0x13d"" hidden=""true"" document=""1"" /> <entry offset=""0x14b"" hidden=""true"" document=""1"" /> <entry offset=""0x14d"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" /> <entry offset=""0x15e"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" /> <entry offset=""0x163"" hidden=""true"" document=""1"" /> <entry offset=""0x165"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" /> <entry offset=""0x16a"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" /> <entry offset=""0x16f"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" /> <entry offset=""0x176"" hidden=""true"" document=""1"" /> <entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" /> <entry offset=""0x182"" hidden=""true"" document=""1"" /> <entry offset=""0x187"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x18c"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" /> <entry offset=""0x191"" hidden=""true"" document=""1"" /> <entry offset=""0x193"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19a"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" /> <entry offset=""0x19f"" hidden=""true"" document=""1"" /> <entry offset=""0x1a1"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" /> <entry offset=""0x1a7"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" /> <entry offset=""0x1ad"" hidden=""true"" document=""1"" /> <entry offset=""0x1b0"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" /> <entry offset=""0x1b1"" hidden=""true"" document=""1"" /> <entry offset=""0x1b4"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b5""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b5"" attributes=""0"" /> <scope startOffset=""0x14d"" endOffset=""0x15e""> <local name=""x"" il_index=""1"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" /> </scope> <scope startOffset=""0x163"" endOffset=""0x16a""> <local name=""y"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> </scope> <scope startOffset=""0x191"" endOffset=""0x198""> <local name=""p"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> <local name=""q"" il_index=""5"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> </scope> <scope startOffset=""0x198"" endOffset=""0x19f""> <local name=""p"" il_index=""6"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" /> </scope> <scope startOffset=""0x19f"" endOffset=""0x1a7""> <local name=""z"" il_index=""7"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_IsPattern() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static bool M() { object obj = F(); return // declaration pattern obj is int x || // discard pattern obj is bool _ || // var pattern obj is var (y, z1) || // constant pattern obj is 4.0 || // positional patterns obj is C() || obj is () || obj is C(int p1, C(int q)) || obj is C(x: int p2) || // property pattern obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @" { // Code size 301 (0x12d) .maxstack 3 .locals init (object V_0, //obj int V_1, //x object V_2, //y object V_3, //z1 int V_4, //p1 int V_5, //q int V_6, //p2 int V_7, //z2 System.Runtime.CompilerServices.ITuple V_8, C V_9, object V_10, C V_11, D V_12, D V_13, bool V_14) -IL_0000: nop -IL_0001: call ""object Program.F()"" IL_0006: stloc.0 -IL_0007: ldloc.0 IL_0008: isinst ""int"" IL_000d: brfalse.s IL_001b IL_000f: ldloc.0 IL_0010: unbox.any ""int"" IL_0015: stloc.1 IL_0016: br IL_0125 IL_001b: ldloc.0 IL_001c: isinst ""bool"" IL_0021: brtrue IL_0125 IL_0026: ldloc.0 IL_0027: isinst ""System.Runtime.CompilerServices.ITuple"" IL_002c: stloc.s V_8 IL_002e: ldloc.s V_8 IL_0030: brfalse.s IL_0053 IL_0032: ldloc.s V_8 IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0039: ldc.i4.2 IL_003a: bne.un.s IL_0053 IL_003c: ldloc.s V_8 IL_003e: ldc.i4.0 IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0044: stloc.2 IL_0045: ldloc.s V_8 IL_0047: ldc.i4.1 IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_004d: stloc.3 IL_004e: br IL_0125 IL_0053: ldloc.0 IL_0054: isinst ""double"" IL_0059: brfalse.s IL_006f IL_005b: ldloc.0 IL_005c: unbox.any ""double"" IL_0061: ldc.r8 4 IL_006a: beq IL_0125 IL_006f: ldloc.0 IL_0070: isinst ""C"" IL_0075: brtrue IL_0125 IL_007a: ldloc.0 IL_007b: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0080: stloc.s V_8 IL_0082: ldloc.s V_8 IL_0084: brfalse.s IL_0092 IL_0086: ldloc.s V_8 IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_008d: brfalse IL_0125 IL_0092: ldloc.0 IL_0093: isinst ""C"" IL_0098: stloc.s V_9 IL_009a: ldloc.s V_9 IL_009c: brfalse.s IL_00c3 IL_009e: ldloc.s V_9 IL_00a0: ldloca.s V_4 IL_00a2: ldloca.s V_10 IL_00a4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00a9: nop IL_00aa: ldloc.s V_10 IL_00ac: isinst ""C"" IL_00b1: stloc.s V_11 IL_00b3: ldloc.s V_11 IL_00b5: brfalse.s IL_00c3 IL_00b7: ldloc.s V_11 IL_00b9: ldloca.s V_5 IL_00bb: callvirt ""void C.Deconstruct(out int)"" IL_00c0: nop IL_00c1: br.s IL_0125 IL_00c3: ldloc.0 IL_00c4: isinst ""C"" IL_00c9: stloc.s V_11 IL_00cb: ldloc.s V_11 IL_00cd: brfalse.s IL_00db IL_00cf: ldloc.s V_11 IL_00d1: ldloca.s V_6 IL_00d3: callvirt ""void C.Deconstruct(out int)"" IL_00d8: nop IL_00d9: br.s IL_0125 IL_00db: ldloc.0 IL_00dc: isinst ""D"" IL_00e1: stloc.s V_12 IL_00e3: ldloc.s V_12 IL_00e5: brfalse.s IL_0122 IL_00e7: ldloc.s V_12 IL_00e9: callvirt ""int D.P.get"" IL_00ee: ldc.i4.1 IL_00ef: bne.un.s IL_0122 IL_00f1: ldloc.s V_12 IL_00f3: callvirt ""D D.Q.get"" IL_00f8: stloc.s V_13 IL_00fa: ldloc.s V_13 IL_00fc: brfalse.s IL_0122 IL_00fe: ldloc.s V_13 IL_0100: callvirt ""int D.P.get"" IL_0105: ldc.i4.2 IL_0106: bne.un.s IL_0122 IL_0108: ldloc.s V_12 IL_010a: callvirt ""C D.R.get"" IL_010f: stloc.s V_11 IL_0111: ldloc.s V_11 IL_0113: brfalse.s IL_0122 IL_0115: ldloc.s V_11 IL_0117: ldloca.s V_7 IL_0119: callvirt ""void C.Deconstruct(out int)"" IL_011e: nop IL_011f: ldc.i4.1 IL_0120: br.s IL_0123 IL_0122: ldc.i4.0 IL_0123: br.s IL_0126 IL_0125: ldc.i4.1 IL_0126: stloc.s V_14 IL_0128: br.s IL_012a -IL_012a: ldloc.s V_14 IL_012c: ret } "); verifier.VerifyPdb("Program.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""230"" /> <slot kind=""0"" offset=""233"" /> <slot kind=""0"" offset=""419"" /> <slot kind=""0"" offset=""429"" /> <slot kind=""0"" offset=""465"" /> <slot kind=""0"" offset=""561"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" /> <entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x12d""> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")] [WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")] [Fact] public void Patterns_SwitchExpression_Closures() { string source = WithWindowsLineBreaks(@" using System; public class C { static int M() { return F() switch { 1 => F() switch { C { P: int p, Q: C { P: int q } } => G(() => p + q), _ => 10 }, 2 => F() switch { C { P: int r } => G(() => r), _ => 20 }, C { Q: int s } => G(() => s), _ => 0 } switch { var t when t > 0 => G(() => t), _ => 0 }; } object P { get; set; } object Q { get; set; } static object F() => null; static int G(Func<int> f) => 0; } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 472 (0x1d8) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1, C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1 int V_3, object V_4, int V_5, C V_6, object V_7, C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2 int V_9, object V_10, C V_11, object V_12, object V_13, C V_14, object V_15, C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3 object V_17, C V_18, object V_19, int V_20) // sequence point: { IL_0000: nop // sequence point: <hidden> IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0006: stloc.0 // sequence point: <hidden> IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()"" IL_000c: stloc.2 IL_000d: call ""object C.F()"" IL_0012: stloc.s V_4 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 // sequence point: switch ... } IL_0017: nop // sequence point: <hidden> IL_0018: ldloc.s V_4 IL_001a: isinst ""int"" IL_001f: brfalse.s IL_003e IL_0021: ldloc.s V_4 IL_0023: unbox.any ""int"" IL_0028: stloc.s V_5 // sequence point: <hidden> IL_002a: ldloc.s V_5 IL_002c: ldc.i4.1 IL_002d: beq.s IL_0075 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_5 IL_0033: ldc.i4.2 IL_0034: beq IL_0116 IL_0039: br IL_0194 IL_003e: ldloc.s V_4 IL_0040: isinst ""C"" IL_0045: stloc.s V_6 IL_0047: ldloc.s V_6 IL_0049: brfalse IL_0194 IL_004e: ldloc.s V_6 IL_0050: callvirt ""object C.Q.get"" IL_0055: stloc.s V_7 // sequence point: <hidden> IL_0057: ldloc.s V_7 IL_0059: isinst ""int"" IL_005e: brfalse IL_0194 IL_0063: ldloc.2 IL_0064: ldloc.s V_7 IL_0066: unbox.any ""int"" IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3"" // sequence point: <hidden> IL_0070: br IL_017e // sequence point: <hidden> IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()"" IL_007a: stloc.s V_8 IL_007c: call ""object C.F()"" IL_0081: stloc.s V_10 IL_0083: ldc.i4.1 IL_0084: brtrue.s IL_0087 // sequence point: switch ... IL_0086: nop // sequence point: <hidden> IL_0087: ldloc.s V_10 IL_0089: isinst ""C"" IL_008e: stloc.s V_11 IL_0090: ldloc.s V_11 IL_0092: brfalse.s IL_0104 IL_0094: ldloc.s V_11 IL_0096: callvirt ""object C.P.get"" IL_009b: stloc.s V_12 // sequence point: <hidden> IL_009d: ldloc.s V_12 IL_009f: isinst ""int"" IL_00a4: brfalse.s IL_0104 IL_00a6: ldloc.s V_8 IL_00a8: ldloc.s V_12 IL_00aa: unbox.any ""int"" IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4"" // sequence point: <hidden> IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""object C.Q.get"" IL_00bb: stloc.s V_13 // sequence point: <hidden> IL_00bd: ldloc.s V_13 IL_00bf: isinst ""C"" IL_00c4: stloc.s V_14 IL_00c6: ldloc.s V_14 IL_00c8: brfalse.s IL_0104 IL_00ca: ldloc.s V_14 IL_00cc: callvirt ""object C.P.get"" IL_00d1: stloc.s V_15 // sequence point: <hidden> IL_00d3: ldloc.s V_15 IL_00d5: isinst ""int"" IL_00da: brfalse.s IL_0104 IL_00dc: ldloc.s V_8 IL_00de: ldloc.s V_15 IL_00e0: unbox.any ""int"" IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5"" // sequence point: <hidden> IL_00ea: br.s IL_00ec // sequence point: <hidden> IL_00ec: br.s IL_00ee // sequence point: G(() => p + q) IL_00ee: ldloc.s V_8 IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()"" IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_00fb: call ""int C.G(System.Func<int>)"" IL_0100: stloc.s V_9 IL_0102: br.s IL_010a // sequence point: 10 IL_0104: ldc.i4.s 10 IL_0106: stloc.s V_9 IL_0108: br.s IL_010a // sequence point: <hidden> IL_010a: ldc.i4.1 IL_010b: brtrue.s IL_010e // sequence point: switch ... } IL_010d: nop // sequence point: F() switch ... IL_010e: ldloc.s V_9 IL_0110: stloc.3 IL_0111: br IL_0198 // sequence point: <hidden> IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()"" IL_011b: stloc.s V_16 IL_011d: call ""object C.F()"" IL_0122: stloc.s V_17 IL_0124: ldc.i4.1 IL_0125: brtrue.s IL_0128 // sequence point: switch ... IL_0127: nop // sequence point: <hidden> IL_0128: ldloc.s V_17 IL_012a: isinst ""C"" IL_012f: stloc.s V_18 IL_0131: ldloc.s V_18 IL_0133: brfalse.s IL_016f IL_0135: ldloc.s V_18 IL_0137: callvirt ""object C.P.get"" IL_013c: stloc.s V_19 // sequence point: <hidden> IL_013e: ldloc.s V_19 IL_0140: isinst ""int"" IL_0145: brfalse.s IL_016f IL_0147: ldloc.s V_16 IL_0149: ldloc.s V_19 IL_014b: unbox.any ""int"" IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6"" // sequence point: <hidden> IL_0155: br.s IL_0157 // sequence point: <hidden> IL_0157: br.s IL_0159 // sequence point: G(() => r) IL_0159: ldloc.s V_16 IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()"" IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0166: call ""int C.G(System.Func<int>)"" IL_016b: stloc.s V_9 IL_016d: br.s IL_0175 // sequence point: 20 IL_016f: ldc.i4.s 20 IL_0171: stloc.s V_9 IL_0173: br.s IL_0175 // sequence point: <hidden> IL_0175: ldc.i4.1 IL_0176: brtrue.s IL_0179 // sequence point: F() switch ... IL_0178: nop // sequence point: F() switch ... IL_0179: ldloc.s V_9 IL_017b: stloc.3 IL_017c: br.s IL_0198 // sequence point: <hidden> IL_017e: br.s IL_0180 // sequence point: G(() => s) IL_0180: ldloc.2 IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()"" IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_018c: call ""int C.G(System.Func<int>)"" IL_0191: stloc.3 IL_0192: br.s IL_0198 // sequence point: 0 IL_0194: ldc.i4.0 IL_0195: stloc.3 IL_0196: br.s IL_0198 // sequence point: <hidden> IL_0198: ldc.i4.1 IL_0199: brtrue.s IL_019c // sequence point: return F() s ... }; IL_019b: nop // sequence point: <hidden> IL_019c: ldloc.0 IL_019d: ldloc.3 IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2"" IL_01a3: ldc.i4.1 IL_01a4: brtrue.s IL_01a7 // sequence point: switch ... } IL_01a6: nop // sequence point: <hidden> IL_01a7: br.s IL_01a9 // sequence point: when t > 0 IL_01a9: ldloc.0 IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2"" IL_01af: ldc.i4.0 IL_01b0: bgt.s IL_01b4 // sequence point: <hidden> IL_01b2: br.s IL_01c8 // sequence point: G(() => t) IL_01b4: ldloc.0 IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()"" IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_01c0: call ""int C.G(System.Func<int>)"" IL_01c5: stloc.1 IL_01c6: br.s IL_01cc // sequence point: 0 IL_01c8: ldc.i4.0 IL_01c9: stloc.1 IL_01ca: br.s IL_01cc // sequence point: <hidden> IL_01cc: ldc.i4.1 IL_01cd: brtrue.s IL_01d0 // sequence point: return F() s ... }; IL_01cf: nop // sequence point: <hidden> IL_01d0: ldloc.1 IL_01d1: stloc.s V_20 IL_01d3: br.s IL_01d5 // sequence point: } IL_01d5: ldloc.s V_20 IL_01d7: ret } "); verifier.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""30"" offset=""22"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""22"" /> <slot kind=""35"" offset=""22"" ordinal=""1"" /> <slot kind=""35"" offset=""22"" ordinal=""2"" /> <slot kind=""35"" offset=""22"" ordinal=""3"" /> <slot kind=""30"" offset=""63"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""63"" /> <slot kind=""35"" offset=""63"" ordinal=""1"" /> <slot kind=""35"" offset=""63"" ordinal=""2"" /> <slot kind=""35"" offset=""63"" ordinal=""3"" /> <slot kind=""35"" offset=""63"" ordinal=""4"" /> <slot kind=""35"" offset=""63"" ordinal=""5"" /> <slot kind=""30"" offset=""238"" /> <slot kind=""35"" offset=""238"" /> <slot kind=""35"" offset=""238"" ordinal=""1"" /> <slot kind=""35"" offset=""238"" ordinal=""2"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <closure offset=""22"" /> <closure offset=""63"" /> <closure offset=""238"" /> <lambda offset=""511"" closure=""0"" /> <lambda offset=""407"" closure=""1"" /> <lambda offset=""157"" closure=""2"" /> <lambda offset=""313"" closure=""3"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" hidden=""true"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x75"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x87"" hidden=""true"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0xb4"" hidden=""true"" document=""1"" /> <entry offset=""0xbd"" hidden=""true"" document=""1"" /> <entry offset=""0xd3"" hidden=""true"" document=""1"" /> <entry offset=""0xea"" hidden=""true"" document=""1"" /> <entry offset=""0xec"" hidden=""true"" document=""1"" /> <entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" /> <entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" /> <entry offset=""0x10a"" hidden=""true"" document=""1"" /> <entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x116"" hidden=""true"" document=""1"" /> <entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" /> <entry offset=""0x128"" hidden=""true"" document=""1"" /> <entry offset=""0x13e"" hidden=""true"" document=""1"" /> <entry offset=""0x155"" hidden=""true"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" /> <entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" /> <entry offset=""0x175"" hidden=""true"" document=""1"" /> <entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" /> <entry offset=""0x17e"" hidden=""true"" document=""1"" /> <entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" /> <entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" /> <entry offset=""0x19c"" hidden=""true"" document=""1"" /> <entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a7"" hidden=""true"" document=""1"" /> <entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" /> <entry offset=""0x1b2"" hidden=""true"" document=""1"" /> <entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" /> <entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" /> <entry offset=""0x1cc"" hidden=""true"" document=""1"" /> <entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" /> <entry offset=""0x1d0"" hidden=""true"" document=""1"" /> <entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1d8""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x1d5""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x1a3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" /> <scope startOffset=""0x75"" endOffset=""0x111""> <local name=""CS$&lt;&gt;8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" /> </scope> <scope startOffset=""0x116"" endOffset=""0x17c""> <local name=""CS$&lt;&gt;8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" /> </scope> </scope> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")] [ConditionalFact(typeof(CoreClrOnly))] public void NestedSwitchExpressions_Closures_01() { string source = WithWindowsLineBreaks( @"using System; class C { static int F(object o) { return o switch { int i => new Func<int>(() => i + i switch { 1 => 2, _ => 3 })(), _ => 4 }; } }"); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyTypeIL("C", @".class private auto ansi beforefieldinit C extends [netstandard]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<i>5__2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a1 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<F>b__0' () cil managed { // Method begins at RVA 0x20ac // Code size 38 (0x26) .maxstack 2 .locals init ( [0] int32, [1] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_0011: ldc.i4.1 IL_0012: beq.s IL_0016 IL_0014: br.s IL_001a IL_0016: ldc.i4.2 IL_0017: stloc.1 IL_0018: br.s IL_001e IL_001a: ldc.i4.3 IL_001b: stloc.1 IL_001c: br.s IL_001e IL_001e: ldc.i4.1 IL_001f: brtrue.s IL_0022 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: add IL_0025: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method private hidebysig static int32 F ( object o ) cil managed { // Method begins at RVA 0x2050 // Code size 69 (0x45) .maxstack 2 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] int32 ) IL_0000: nop IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: isinst [netstandard]System.Int32 IL_0011: brfalse.s IL_0037 IL_0013: ldloc.0 IL_0014: ldarg.0 IL_0015: unbox.any [netstandard]System.Int32 IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_001f: br.s IL_0021 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'() IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int) IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke() IL_0034: stloc.1 IL_0035: br.s IL_003b IL_0037: ldc.i4.4 IL_0038: stloc.1 IL_0039: br.s IL_003b IL_003b: ldc.i4.1 IL_003c: brtrue.s IL_003f IL_003e: nop IL_003f: ldloc.1 IL_0040: stloc.2 IL_0041: br.s IL_0043 IL_0043: ldloc.2 IL_0044: ret } // end of method C::F .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a1 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C::.ctor } // end of class C "); verifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""80"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" /> <entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x45""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x43""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> <encLocalSlotMap> <slot kind=""28"" offset=""86"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0x1e"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")] [ConditionalFact(typeof(CoreClrOnly))] public void NestedSwitchExpressions_Closures_02() { string source = WithWindowsLineBreaks( @"using System; class C { static string F(object o) { return o switch { int i => new Func<string>(() => ""1"" + i switch { 1 => new Func<string>(() => ""2"" + i)(), _ => ""3"" })(), _ => ""4"" }; } }"); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyTypeIL("C", @".class private auto ansi beforefieldinit C extends [netstandard]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<i>5__2' .field public class [netstandard]System.Func`1<string> '<>9__1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a5 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance string '<F>b__0' () cil managed { // Method begins at RVA 0x20b0 // Code size 78 (0x4e) .maxstack 3 .locals init ( [0] string, [1] class [netstandard]System.Func`1<string> ) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.0 IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_000a: ldc.i4.1 IL_000b: beq.s IL_000f IL_000d: br.s IL_0036 IL_000f: ldarg.0 IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1' IL_0015: dup IL_0016: brtrue.s IL_002e IL_0018: pop IL_0019: ldarg.0 IL_001a: ldarg.0 IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'() IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int) IL_0026: dup IL_0027: stloc.1 IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1' IL_002d: ldloc.1 IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke() IL_0033: stloc.0 IL_0034: br.s IL_003e IL_0036: ldstr ""3"" IL_003b: stloc.0 IL_003c: br.s IL_003e IL_003e: ldc.i4.1 IL_003f: brtrue.s IL_0042 IL_0041: nop IL_0042: ldstr ""1"" IL_0047: ldloc.0 IL_0048: call string [netstandard]System.String::Concat(string, string) IL_004d: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__0' .method assembly hidebysig instance string '<F>b__1' () cil managed { // Method begins at RVA 0x210a // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr ""2"" IL_0005: ldarg.0 IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_000b: call instance string [netstandard]System.Int32::ToString() IL_0010: call string [netstandard]System.String::Concat(string, string) IL_0015: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method private hidebysig static string F ( object o ) cil managed { // Method begins at RVA 0x2050 // Code size 73 (0x49) .maxstack 2 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] string, [2] string ) IL_0000: nop IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: isinst [netstandard]System.Int32 IL_0011: brfalse.s IL_0037 IL_0013: ldloc.0 IL_0014: ldarg.0 IL_0015: unbox.any [netstandard]System.Int32 IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_001f: br.s IL_0021 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'() IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int) IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke() IL_0034: stloc.1 IL_0035: br.s IL_003f IL_0037: ldstr ""4"" IL_003c: stloc.1 IL_003d: br.s IL_003f IL_003f: ldc.i4.1 IL_0040: brtrue.s IL_0043 IL_0042: nop IL_0043: ldloc.1 IL_0044: stloc.2 IL_0045: br.s IL_0047 IL_0047: ldloc.2 IL_0048: ret } // end of method C::F .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a5 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C::.ctor } // end of class C "); verifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""83"" closure=""0"" /> <lambda offset=""158"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" /> <entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" /> <entry offset=""0x43"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x49""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x47""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" /> <entry offset=""0x3e"" hidden=""true"" document=""1"" /> <entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x42"" hidden=""true"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SwitchExpression_MethodBody() { string source = @" using System; public class C { static int M() => F() switch { 1 => 1, C { P: int p, Q: C { P: int q } } => G(() => p + q), _ => 0 }; object P { get; set; } object Q { get; set; } static object F() => null; static int G(Func<int> f) => 0; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 171 (0xab) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1, object V_2, int V_3, C V_4, object V_5, object V_6, C V_7, object V_8) // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: call ""object C.F()"" IL_000b: stloc.2 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 // sequence point: switch ... } IL_000f: nop // sequence point: <hidden> IL_0010: ldloc.2 IL_0011: isinst ""int"" IL_0016: brfalse.s IL_0025 IL_0018: ldloc.2 IL_0019: unbox.any ""int"" IL_001e: stloc.3 // sequence point: <hidden> IL_001f: ldloc.3 IL_0020: ldc.i4.1 IL_0021: beq.s IL_0087 IL_0023: br.s IL_00a1 IL_0025: ldloc.2 IL_0026: isinst ""C"" IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brfalse.s IL_00a1 IL_0031: ldloc.s V_4 IL_0033: callvirt ""object C.P.get"" IL_0038: stloc.s V_5 // sequence point: <hidden> IL_003a: ldloc.s V_5 IL_003c: isinst ""int"" IL_0041: brfalse.s IL_00a1 IL_0043: ldloc.0 IL_0044: ldloc.s V_5 IL_0046: unbox.any ""int"" IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2"" // sequence point: <hidden> IL_0050: ldloc.s V_4 IL_0052: callvirt ""object C.Q.get"" IL_0057: stloc.s V_6 // sequence point: <hidden> IL_0059: ldloc.s V_6 IL_005b: isinst ""C"" IL_0060: stloc.s V_7 IL_0062: ldloc.s V_7 IL_0064: brfalse.s IL_00a1 IL_0066: ldloc.s V_7 IL_0068: callvirt ""object C.P.get"" IL_006d: stloc.s V_8 // sequence point: <hidden> IL_006f: ldloc.s V_8 IL_0071: isinst ""int"" IL_0076: brfalse.s IL_00a1 IL_0078: ldloc.0 IL_0079: ldloc.s V_8 IL_007b: unbox.any ""int"" IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3"" // sequence point: <hidden> IL_0085: br.s IL_008b // sequence point: 1 IL_0087: ldc.i4.1 IL_0088: stloc.1 IL_0089: br.s IL_00a5 // sequence point: <hidden> IL_008b: br.s IL_008d // sequence point: G(() => p + q) IL_008d: ldloc.0 IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()"" IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0099: call ""int C.G(System.Func<int>)"" IL_009e: stloc.1 IL_009f: br.s IL_00a5 // sequence point: 0 IL_00a1: ldc.i4.0 IL_00a2: stloc.1 IL_00a3: br.s IL_00a5 // sequence point: <hidden> IL_00a5: ldc.i4.1 IL_00a6: brtrue.s IL_00a9 // sequence point: F() switch ... } IL_00a8: nop // sequence point: <hidden> IL_00a9: ldloc.1 IL_00aa: ret } "); verifier.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""7"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""7"" /> <slot kind=""35"" offset=""7"" ordinal=""1"" /> <slot kind=""35"" offset=""7"" ordinal=""2"" /> <slot kind=""35"" offset=""7"" ordinal=""3"" /> <slot kind=""35"" offset=""7"" ordinal=""4"" /> <slot kind=""35"" offset=""7"" ordinal=""5"" /> <slot kind=""35"" offset=""7"" ordinal=""6"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""7"" /> <lambda offset=""92"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x50"" hidden=""true"" document=""1"" /> <entry offset=""0x59"" hidden=""true"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x8b"" hidden=""true"" document=""1"" /> <entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" /> <entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" /> <entry offset=""0xa5"" hidden=""true"" document=""1"" /> <entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xab""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SwitchExpression_MethodBody_02() { string source = @" using System; public class C { static Action M1(int x) => () => { _ = x; }; static Action M2(int x) => x switch { _ => () => { _ = x; } }; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @" { // Code size 26 (0x1a) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""int C.<>c__DisplayClass0_0.x"" // sequence point: () => { _ = x; } IL_000d: ldloc.0 IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()"" IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0019: ret } "); verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @" { // Code size 40 (0x28) .maxstack 2 .locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Action V_1) // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""int C.<>c__DisplayClass1_0.x"" // sequence point: x switch { _ => () => { _ = x; } } IL_000d: ldc.i4.1 IL_000e: brtrue.s IL_0011 // sequence point: switch { _ => () => { _ = x; } } IL_0010: nop // sequence point: <hidden> IL_0011: br.s IL_0013 // sequence point: () => { _ = x; } IL_0013: ldloc.0 IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()"" IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001f: stloc.1 IL_0020: br.s IL_0022 // sequence point: <hidden> IL_0022: ldc.i4.1 IL_0023: brtrue.s IL_0026 // sequence point: x switch { _ => () => { _ = x; } } IL_0025: nop // sequence point: <hidden> IL_0026: ldloc.1 IL_0027: ret } "); verifier.VerifyPdb("C.M1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M1"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""9"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); verifier.VerifyPdb("C.M2", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M2"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <lambda offset=""25"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x26"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SyntaxOffset_OutVarInInitializers_SwitchExpression() { var source = @"class C { static int G(out int x) => throw null; static int F(System.Func<int> x) => throw null; C() { } int y1 = G(out var z) switch { _ => F(() => z) }; // line 7 } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-26"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""-26"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-26"" /> <lambda offset=""-4"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" /> <entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" /> <entry offset=""0x2c"" hidden=""true"" document=""1"" /> <entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" /> <entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" /> <entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <scope startOffset=""0x0"" endOffset=""0x37""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")] [Fact] public void HiddenSequencePointAtSwitchExpressionFinalMergePoint() { var source = @"class C { static int M(int x) { var y = x switch { 1 => 2, _ => 3, }; return y; } } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 31 (0x1f) .maxstack 2 .locals init (int V_0, //y int V_1, int V_2) // sequence point: { IL_0000: nop // sequence point: var y = x sw ... }; IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 // sequence point: switch ... } IL_0004: nop // sequence point: <hidden> IL_0005: ldarg.0 IL_0006: ldc.i4.1 IL_0007: beq.s IL_000b IL_0009: br.s IL_000f // sequence point: 2 IL_000b: ldc.i4.2 IL_000c: stloc.1 IL_000d: br.s IL_0013 // sequence point: 3 IL_000f: ldc.i4.3 IL_0010: stloc.1 IL_0011: br.s IL_0013 // sequence point: <hidden> IL_0013: ldc.i4.1 IL_0014: brtrue.s IL_0017 // sequence point: var y = x sw ... }; IL_0016: nop // sequence point: <hidden> IL_0017: ldloc.1 IL_0018: stloc.0 // sequence point: return y; IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_001d // sequence point: } IL_001d: ldloc.2 IL_001e: ret } "); } [WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")] [WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")] [Fact] public void Patterns_SwitchStatement_Constant() { string source = WithWindowsLineBreaks( @"class Program { static void M(object o) { switch (o) { case 1 when o == null: case 4: case 2 when o == null: break; case 1 when o != null: case 5: case 3 when o != null: break; default: break; case 1: break; } switch (o) { case 1: break; default: break; } switch (o) { default: break; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source, expectedIL: @"{ // Code size 123 (0x7b) .maxstack 2 .locals init (object V_0, int V_1, object V_2, object V_3, int V_4, object V_5, object V_6, object V_7) // sequence point: { IL_0000: nop // sequence point: switch (o) IL_0001: ldarg.0 IL_0002: stloc.2 // sequence point: <hidden> IL_0003: ldloc.2 IL_0004: stloc.0 // sequence point: <hidden> IL_0005: ldloc.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_004a IL_000d: ldloc.0 IL_000e: unbox.any ""int"" IL_0013: stloc.1 // sequence point: <hidden> IL_0014: ldloc.1 IL_0015: ldc.i4.1 IL_0016: sub IL_0017: switch ( IL_0032, IL_0037, IL_0043, IL_003c, IL_0048) IL_0030: br.s IL_004a // sequence point: when o == null IL_0032: ldarg.0 IL_0033: brfalse.s IL_003c // sequence point: <hidden> IL_0035: br.s IL_003e // sequence point: when o == null IL_0037: ldarg.0 IL_0038: brfalse.s IL_003c // sequence point: <hidden> IL_003a: br.s IL_004a // sequence point: break; IL_003c: br.s IL_004e // sequence point: when o != null IL_003e: ldarg.0 IL_003f: brtrue.s IL_0048 // sequence point: <hidden> IL_0041: br.s IL_004c // sequence point: when o != null IL_0043: ldarg.0 IL_0044: brtrue.s IL_0048 // sequence point: <hidden> IL_0046: br.s IL_004a // sequence point: break; IL_0048: br.s IL_004e // sequence point: break; IL_004a: br.s IL_004e // sequence point: break; IL_004c: br.s IL_004e // sequence point: switch (o) IL_004e: ldarg.0 IL_004f: stloc.s V_5 // sequence point: <hidden> IL_0051: ldloc.s V_5 IL_0053: stloc.3 // sequence point: <hidden> IL_0054: ldloc.3 IL_0055: isinst ""int"" IL_005a: brfalse.s IL_006d IL_005c: ldloc.3 IL_005d: unbox.any ""int"" IL_0062: stloc.s V_4 // sequence point: <hidden> IL_0064: ldloc.s V_4 IL_0066: ldc.i4.1 IL_0067: beq.s IL_006b IL_0069: br.s IL_006d // sequence point: break; IL_006b: br.s IL_006f // sequence point: break; IL_006d: br.s IL_006f // sequence point: switch (o) IL_006f: ldarg.0 IL_0070: stloc.s V_7 // sequence point: <hidden> IL_0072: ldloc.s V_7 IL_0074: stloc.s V_6 // sequence point: <hidden> IL_0076: br.s IL_0078 // sequence point: break; IL_0078: br.s IL_007a // sequence point: } IL_007a: ret }"); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""35"" offset=""378"" /> <slot kind=""35"" offset=""378"" ordinal=""1"" /> <slot kind=""1"" offset=""378"" /> <slot kind=""35"" offset=""511"" /> <slot kind=""1"" offset=""511"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" hidden=""true"" document=""1"" /> <entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" /> <entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" /> <entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" /> <entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x51"" hidden=""true"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" /> <entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x76"" hidden=""true"" document=""1"" /> <entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" /> <entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchStatement_Tuple() { string source = WithWindowsLineBreaks(@" public class C { static int F(int i) { switch (G()) { case (1, 2): return 3; default: return 0; }; } static (object, object) G() => (2, 3); }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); var cv = CompileAndVerify(c); cv.VerifyIL("C.F", @" { // Code size 80 (0x50) .maxstack 2 .locals init (System.ValueTuple<object, object> V_0, object V_1, int V_2, object V_3, int V_4, System.ValueTuple<object, object> V_5, int V_6) IL_0000: nop IL_0001: call ""System.ValueTuple<object, object> C.G()"" IL_0006: stloc.s V_5 IL_0008: ldloc.s V_5 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1"" IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: isinst ""int"" IL_0018: brfalse.s IL_0048 IL_001a: ldloc.1 IL_001b: unbox.any ""int"" IL_0020: stloc.2 IL_0021: ldloc.2 IL_0022: ldc.i4.1 IL_0023: bne.un.s IL_0048 IL_0025: ldloc.0 IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2"" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: isinst ""int"" IL_0032: brfalse.s IL_0048 IL_0034: ldloc.3 IL_0035: unbox.any ""int"" IL_003a: stloc.s V_4 IL_003c: ldloc.s V_4 IL_003e: ldc.i4.2 IL_003f: beq.s IL_0043 IL_0041: br.s IL_0048 IL_0043: ldc.i4.3 IL_0044: stloc.s V_6 IL_0046: br.s IL_004d IL_0048: ldc.i4.0 IL_0049: stloc.s V_6 IL_004b: br.s IL_004d IL_004d: ldloc.s V_6 IL_004f: ret } "); c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""35"" offset=""11"" ordinal=""2"" /> <slot kind=""35"" offset=""11"" ordinal=""3"" /> <slot kind=""35"" offset=""11"" ordinal=""4"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Tuples [Fact] public void SyntaxOffset_TupleDeconstruction() { var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""7"" /> <slot kind=""0"" offset=""18"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" /> <entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" /> <entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> <local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestDeconstruction() { var source = @" public class C { public static (int, int) F() => (1, 2); public static void Main() { int x, y; (x, y) = F(); System.Console.WriteLine(x + y); } } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0, //x int V_1) //y // sequence point: { IL_0000: nop // sequence point: (x, y) = F(); IL_0001: call ""System.ValueTuple<int, int> C.F()"" IL_0006: dup IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000c: stloc.0 IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0012: stloc.1 // sequence point: System.Console.WriteLine(x + y); IL_0013: ldloc.0 IL_0014: ldloc.1 IL_0015: add IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop // sequence point: } IL_001c: ret } ", sequencePoints: "C.Main", source: source); } [Fact] public void SyntaxOffset_TupleParenthesized() { var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""20"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" /> <entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" /> <entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x33""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" /> </scope> </method> </methods> </symbols>" ); } [Fact] public void SyntaxOffset_TupleVarDefined() { var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""6"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" /> <entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" /> <entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared() { var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" /> <entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" /> <entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region OutVar [Fact] public void SyntaxOffset_OutVarInConstructor() { var source = @" class B { B(out int z) { z = 2; } } class C { int F = G(out var v1); int P => G(out var v2); C() : base(out var v3) { G(out var v4); } int G(out int x) { x = 1; return 2; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics( // (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)' // int F = G(out var v1); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13), // (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments // : base(out var v3) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7)); } [Fact] public void SyntaxOffset_OutVarInMethod() { var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""6"" /> <slot kind=""0"" offset=""23"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" /> <entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" /> <entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" /> <entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" /> <entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> <local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_01() { var source = WithWindowsLineBreaks( @" class C : A { int x = G(out var x); int y {get;} = G(out var y); C() : base(G(out var z)) { } static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-36"" /> <slot kind=""0"" offset=""-22"" /> <slot kind=""0"" offset=""-3"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" /> <entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" /> <entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> <scope startOffset=""0xd"" endOffset=""0x1a""> <local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" /> </scope> <scope startOffset=""0x1a"" endOffset=""0x2a""> <local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_02() { var source = WithWindowsLineBreaks( @" class C : A { C() : base(G(out var x)) { int y = 1; y++; } static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-3"" /> <slot kind=""0"" offset=""16"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" /> <entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" /> <entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x16""> <local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_03() { var source = WithWindowsLineBreaks( @" class C : A { C() : base(G(out var x)) => G(out var y); static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-3"" /> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x17""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x17""> <local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_04() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } C() { } #line 2000 int y1 = G(out var z) + F(() => z); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-25"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" /> <entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x32""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass2_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_05() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } #line 2000 int y1 { get; } = G(out var z) + F(() => z); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>5</methodOrdinal> <closure offset=""-25"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x31""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass5_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_06() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } #line 2000 int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @" { // Code size 90 (0x5a) .maxstack 4 .locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0 C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1 ~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()"" IL_0005: stloc.0 -IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z"" IL_000d: call ""int C.G(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.F(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.y1"" ~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()"" IL_002e: stloc.1 -IL_002f: ldarg.0 IL_0030: ldloc.1 IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u"" IL_0036: call ""int C.G(out int)"" IL_003b: ldloc.1 IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()"" IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0047: call ""int C.F(System.Func<int>)"" IL_004c: add IL_004d: stfld ""int C.y2"" IL_0052: ldarg.0 IL_0053: call ""object..ctor()"" IL_0058: nop IL_0059: ret } "); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-52"" /> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <closure offset=""-52"" /> <closure offset=""-25"" /> <lambda offset=""-29"" closure=""0"" /> <lambda offset=""-2"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x5a""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> <scope startOffset=""0x29"" endOffset=""0x52""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass4_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass4_1"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_07() { var source = WithWindowsLineBreaks( @" class C : A { #line 2000 C() : base(G(out var z)+ F(() => z)) { } static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-3"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" /> <entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" /> <entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2c""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInQuery_01() { var source = WithWindowsLineBreaks( @" using System.Linq; class C { C() { var q = from a in new [] {1} where G(out var x1) > a select a; } static int G(out int x) { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""88"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" /> <entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x38""> <namespace name=""System.Linq"" /> <scope startOffset=""0x7"" endOffset=""0x38""> <local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c.<.ctor>b__0_0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""98"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInQuery_02() { var source = WithWindowsLineBreaks( @" using System.Linq; class C { C() #line 2000 { var q = from a in new [] {1} where G(out var x1) > F(() => x1) select a; } static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""88"" /> <lambda offset=""88"" /> <lambda offset=""112"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" /> <entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x38""> <namespace name=""System.Linq"" /> <scope startOffset=""0x7"" endOffset=""0x38""> <local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c.<.ctor>b__0_0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""30"" offset=""88"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x25""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInSwitchExpression() { var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""16"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" /> <entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" /> <entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" /> <entry offset=""0x2f"" hidden=""true"" document=""1"" /> <entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3a""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } #endregion [WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")] [Fact] public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint() { var source = WithWindowsLineBreaks( @"#line 1 ""C:\Async.cs"" #pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE"" using System.Threading.Tasks; public class C { public async void M1() { } } "); var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs"); var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true)); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" /> <file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" /> </files> <methods> <method containingType=""C"" name=""M1""> <customDebugInfo> <forwardIterator name=""&lt;M1&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""C+&lt;M1&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x37""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <catchHandler offset=""0xa"" /> <kickoffMethod declaringType=""C"" methodName=""M1"" /> </asyncInfo> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" /> <file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" /> </files> <methods> <method containingType=""C+&lt;M1&gt;d__0"" name=""MoveNext""> <customDebugInfo> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""2"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" /> <entry offset=""0xa"" hidden=""true"" document=""2"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" /> <entry offset=""0x2a"" hidden=""true"" document=""2"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa"" /> <kickoffMethod declaringType=""C"" methodName=""M1"" /> </asyncInfo> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")] [Fact] public void SequencePointsForConstructorWithHiddenInitializer() { string initializerSource = WithWindowsLineBreaks(@" #line hidden partial class C { int i = 42; } "); string constructorSource = WithWindowsLineBreaks(@" partial class C { C() { } } "); var c = CreateCompilation( new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" /> <file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" /> <file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""2"" /> <entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] [Fact] public void LocalFunctionSequencePoints() { string source = WithWindowsLineBreaks( @"class Program { static int Main(string[] args) { // 4 int Local1(string[] a) => a.Length; // 7 int Local2(string[] a) { // 9 return a.Length; // 10 } // 11 return Local1(args) + Local2(args); // 12 } // 13 }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""115"" /> <lambda offset=""202"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Program"" name=""&lt;Main&gt;g__Local1|0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> <method containingType=""Program"" name=""&lt;Main&gt;g__Local2|0_1"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""202"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void SwitchInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { int i = 0; switch (i) { case 1: break; } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 89 (0x59) .maxstack 2 .locals init (int V_0, int V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: switch (i) IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0016: stloc.1 // sequence point: <hidden> IL_0017: ldloc.1 IL_0018: stfld ""int Program.<Test>d__0.<>s__2"" // sequence point: <hidden> IL_001d: ldarg.0 IL_001e: ldfld ""int Program.<Test>d__0.<>s__2"" IL_0023: ldc.i4.1 IL_0024: beq.s IL_0028 IL_0026: br.s IL_002a // sequence point: break; IL_0028: br.s IL_002a // sequence point: <hidden> IL_002a: leave.s IL_0044 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_002c: stloc.2 IL_002d: ldarg.0 IL_002e: ldc.i4.s -2 IL_0030: stfld ""int Program.<Test>d__0.<>1__state"" IL_0035: ldarg.0 IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_003b: ldloc.2 IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0041: nop IL_0042: leave.s IL_0058 } // sequence point: } IL_0044: ldarg.0 IL_0045: ldc.i4.s -2 IL_0047: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_004c: ldarg.0 IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0057: nop IL_0058: ret }", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void WhileInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { int i = 0; while (i == 1) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 83 (0x53) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_000f: br.s IL_0017 // sequence point: Console.WriteLine(); IL_0011: call ""void System.Console.WriteLine()"" IL_0016: nop // sequence point: while (i == 1) IL_0017: ldarg.0 IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_001d: ldc.i4.1 IL_001e: ceq IL_0020: stloc.1 // sequence point: <hidden> IL_0021: ldloc.1 IL_0022: brtrue.s IL_0011 IL_0024: leave.s IL_003e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0026: stloc.2 IL_0027: ldarg.0 IL_0028: ldc.i4.s -2 IL_002a: stfld ""int Program.<Test>d__0.<>1__state"" IL_002f: ldarg.0 IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0035: ldloc.2 IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_003b: nop IL_003c: leave.s IL_0052 } // sequence point: } IL_003e: ldarg.0 IL_003f: ldc.i4.s -2 IL_0041: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0046: ldarg.0 IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0051: nop IL_0052: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ForInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { for (int i = 0; i > 1; i--) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 99 (0x63) .maxstack 3 .locals init (int V_0, int V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0 IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_000f: br.s IL_0027 // sequence point: Console.WriteLine(); IL_0011: call ""void System.Console.WriteLine()"" IL_0016: nop // sequence point: i-- IL_0017: ldarg.0 IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_001d: stloc.1 IL_001e: ldarg.0 IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: sub IL_0022: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: i > 1 IL_0027: ldarg.0 IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_002d: ldc.i4.1 IL_002e: cgt IL_0030: stloc.2 // sequence point: <hidden> IL_0031: ldloc.2 IL_0032: brtrue.s IL_0011 IL_0034: leave.s IL_004e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0036: stloc.3 IL_0037: ldarg.0 IL_0038: ldc.i4.s -2 IL_003a: stfld ""int Program.<Test>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0045: ldloc.3 IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_004b: nop IL_004c: leave.s IL_0062 } // sequence point: } IL_004e: ldarg.0 IL_004f: ldc.i4.s -2 IL_0051: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0061: nop IL_0062: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ForWithInnerLocalsInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { for (int i = M(out var x); i > 1; i--) Console.WriteLine(); } public static int M(out int x) { x = 0; return 0; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, int V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = M(out var x) IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2"" IL_000f: call ""int Program.M(out int)"" IL_0014: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_0019: br.s IL_0031 // sequence point: Console.WriteLine(); IL_001b: call ""void System.Console.WriteLine()"" IL_0020: nop // sequence point: i-- IL_0021: ldarg.0 IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0027: stloc.1 IL_0028: ldarg.0 IL_0029: ldloc.1 IL_002a: ldc.i4.1 IL_002b: sub IL_002c: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: i > 1 IL_0031: ldarg.0 IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0037: ldc.i4.1 IL_0038: cgt IL_003a: stloc.2 // sequence point: <hidden> IL_003b: ldloc.2 IL_003c: brtrue.s IL_001b IL_003e: leave.s IL_0058 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0040: stloc.3 IL_0041: ldarg.0 IL_0042: ldc.i4.s -2 IL_0044: stfld ""int Program.<Test>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004f: ldloc.3 IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0055: nop IL_0056: leave.s IL_006c } // sequence point: } IL_0058: ldarg.0 IL_0059: ldc.i4.s -2 IL_005b: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0060: ldarg.0 IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_006b: nop IL_006c: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidCharacterInPdbPath() { using (var outStream = Temp.CreateFile().Open()) { var compilation = CreateCompilation(""); var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded)); // This is fine because EmitOptions just controls what is written into the PE file and it's // valid for this to be an illegal file name (path map can easily create these). Assert.True(result.Success); } } [Fact] [WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")] public void FilesOneWithNoMethodBody() { string source1 = WithWindowsLineBreaks(@" using System; class C { public static void Main() { Console.WriteLine(); } } "); string source2 = WithWindowsLineBreaks(@" // no code "); var tree1 = Parse(source1, "f:/build/goo.cs"); var tree2 = Parse(source2, "f:/build/nocode.cs"); var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" /> <file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> </scope> </method> </methods> </symbols> "); } [Fact] [WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")] public void SingleFileWithNoMethodBody() { string source = WithWindowsLineBreaks(@" // no code "); var tree = Parse(source, "f:/build/nocode.cs"); var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" /> </files> <methods /> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBTests : CSharpPDBTestBase { private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef }; #region General [Fact] public void EmitDebugInfoForSourceTextWithoutEncoding1() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A { }", encoding: null, path: "Foo.cs"); var tree2 = SyntaxFactory.ParseSyntaxTree("class B { }", encoding: null, path: ""); var tree3 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class C { }", encoding: null), path: "Bar.cs"); var tree4 = SyntaxFactory.ParseSyntaxTree("class D { }", encoding: Encoding.UTF8, path: "Baz.cs"); var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream()); result.Diagnostics.Verify( // Foo.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding. Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class A { }").WithLocation(1, 1), // Bar.cs(1,1): error CS8055: Cannot emit debug information for a source text without encoding. Diagnostic(ErrorCode.ERR_EncodinglessSyntaxTree, "class C { }").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitDebugInfoForSourceTextWithoutEncoding2() { var tree1 = SyntaxFactory.ParseSyntaxTree("class A { public void F() { } }", encoding: Encoding.Unicode, path: "Foo.cs"); var tree2 = SyntaxFactory.ParseSyntaxTree("class B { public void F() { } }", encoding: null, path: ""); var tree3 = SyntaxFactory.ParseSyntaxTree("class C { public void F() { } }", encoding: new UTF8Encoding(true, false), path: "Bar.cs"); var tree4 = SyntaxFactory.ParseSyntaxTree(SourceText.From("class D { public void F() { } }", new UTF8Encoding(false, false)), path: "Baz.cs"); var comp = CSharpCompilation.Create("Compilation", new[] { tree1, tree2, tree3, tree4 }, new[] { MscorlibRef }, options: TestOptions.ReleaseDll); var result = comp.Emit(new MemoryStream(), pdbStream: new MemoryStream()); result.Diagnostics.Verify(); Assert.True(result.Success); var hash1 = CryptographicHashProvider.ComputeSha1(Encoding.Unicode.GetBytesWithPreamble(tree1.ToString())).ToArray(); var hash3 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(true, false).GetBytesWithPreamble(tree3.ToString())).ToArray(); var hash4 = CryptographicHashProvider.ComputeSha1(new UTF8Encoding(false, false).GetBytesWithPreamble(tree4.ToString())).ToArray(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""Foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash1) + @""" /> <file id=""2"" name="""" language=""C#"" /> <file id=""3"" name=""Bar.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash3) + @""" /> <file id=""4"" name=""Baz.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""" + BitConverter.ToString(hash4) + @""" /> </files> </symbols>", options: PdbValidationOptions.ExcludeMethods); } [WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")] [ConditionalFact(typeof(WindowsOnly))] public void RelativePathForExternalSource_Sha1_Windows() { var text1 = WithWindowsLineBreaks(@" #pragma checksum ""..\Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081"" public class C { public void InitializeComponent() { #line 4 ""..\Test2.cs"" InitializeComponent(); #line default } } "); var compilation = CreateCompilation( new[] { Parse(text1, @"C:\Folder1\Folder2\Test1.cs") }, options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""C:\Folder1\Folder2\Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""40-A6-20-02-2E-60-7D-4F-2D-A8-F4-A6-ED-2E-0E-49-8D-9F-D7-EB"" /> <file id=""2"" name=""C:\Folder1\Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" /> </files> <methods> <method containingType=""C"" name=""InitializeComponent""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(846584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846584")] [ConditionalFact(typeof(UnixLikeOnly))] public void RelativePathForExternalSource_Sha1_Unix() { var text1 = WithWindowsLineBreaks(@" #pragma checksum ""../Test2.cs"" ""{406ea660-64cf-4c82-b6f0-42d48172a799}"" ""BA8CBEA9C2EFABD90D53B616FB80A081"" public class C { public void InitializeComponent() { #line 4 ""../Test2.cs"" InitializeComponent(); #line default } } "); var compilation = CreateCompilation( new[] { Parse(text1, @"/Folder1/Folder2/Test1.cs") }, options: TestOptions.DebugDll.WithSourceReferenceResolver(SourceFileResolver.Default)); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""/Folder1/Folder2/Test1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""82-08-07-BA-BA-52-02-D8-1D-1F-7C-E7-95-8A-6C-04-64-FF-50-31"" /> <file id=""2"" name=""/Folder1/Test2.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""BA-8C-BE-A9-C2-EF-AB-D9-0D-53-B6-16-FB-80-A0-81"" /> </files> <methods> <method containingType=""C"" name=""InitializeComponent""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""39"" endLine=""6"" endColumn=""40"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""9"" endLine=""4"" endColumn=""31"" document=""2"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = _ => new MockSymUnmanagedWriter() }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'MockSymUnmanagedWriter error message' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("MockSymUnmanagedWriter error message")); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors2() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'The version of Windows PDB writer is older than required: '<lib name>'' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterOlderVersionThanRequired, "<lib name>"))); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors3() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0, options: TestOptions.DebugDll.WithDeterministic(true)); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = SymWriterTestUtilities.ThrowingFactory }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'Windows PDB writer doesn't support deterministic compilation: '<lib name>'' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments(string.Format(CodeAnalysisResources.SymWriterNotDeterministic, "<lib name>"))); Assert.False(result.Success); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SymWriterErrors4() { var source0 = @"class C { }"; var compilation = CreateCompilation(source0); // Verify full metadata contains expected rows. var result = compilation.Emit( peStream: new MemoryStream(), metadataPEStream: null, pdbStream: new MemoryStream(), xmlDocumentationStream: null, cancellationToken: default, win32Resources: null, manifestResources: null, options: null, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, rebuildData: null, testData: new CompilationTestData() { SymWriterFactory = _ => throw new DllNotFoundException("xxx") }); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'xxx' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("xxx")); Assert.False(result.Success); } [WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")] [Fact] public void SuppressDynamicAndEncCDIForWinRT() { var source = @" public class C { public static void F() { dynamic a = 1; int b = 2; foreach (var x in new[] { 1,2,3 }) { System.Console.WriteLine(a * b); } } } "; var debug = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.DebugWinMD); debug.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0xb"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" /> <entry offset=""0xe6"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xeb"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf4"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xf5""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xf5"" attributes=""0"" /> <scope startOffset=""0x24"" endOffset=""0xe7""> <local name=""x"" il_index=""4"" il_start=""0x24"" il_end=""0xe7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); var release = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseWinMD); release.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x9"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x22"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x26"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""45"" document=""1"" /> <entry offset=""0xdd"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xea"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xeb""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x0"" il_end=""0xeb"" attributes=""0"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); } [WorkItem(1067635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067635")] [Fact] public void SuppressTupleElementNamesCDIForWinRT() { var source = @"class C { static void F() { (int A, int B) o = (1, 2); } }"; var debug = CreateCompilation(source, options: TestOptions.DebugWinMD); debug.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); var release = CreateCompilation(source, options: TestOptions.ReleaseWinMD); release.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb, options: PdbValidationOptions.SkipConversionValidation); } [Fact] public void DuplicateDocuments() { var source1 = @"class C { static void F() { } }"; var source2 = @"class D { static void F() { } }"; var tree1 = Parse(source1, @"foo.cs"); var tree2 = Parse(source2, @"foo.cs"); var comp = CreateCompilation(new[] { tree1, tree2 }); // the first file wins (checksum CB 22 ...) comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""foo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""CB-22-D8-03-D3-27-32-64-2C-BC-7D-67-5D-E3-CB-AC-D1-64-25-83"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> <method containingType=""D"" name=""F""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""29"" endLine=""1"" endColumn=""30"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void CustomDebugEntryPoint_DLL() { var source = @"class C { static void F() { } }"; var c = CreateCompilation(source, options: TestOptions.DebugDll); var f = c.GetMember<MethodSymbol>("C.F"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""F"" /> <methods/> </symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation); var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol())); int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress; Assert.Equal(0, peEntryPointToken); } [Fact] public void CustomDebugEntryPoint_EXE() { var source = @"class M { static void Main() { } } class C { static void F<S>() { } }"; var c = CreateCompilation(source, options: TestOptions.DebugExe); var f = c.GetMember<MethodSymbol>("C.F"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""F"" /> <methods/> </symbols>", debugEntryPoint: f.GetPublicSymbol(), options: PdbValidationOptions.ExcludeScopes | PdbValidationOptions.ExcludeSequencePoints | PdbValidationOptions.ExcludeCustomDebugInformation); var peReader = new PEReader(c.EmitToArray(debugEntryPoint: f.GetPublicSymbol())); int peEntryPointToken = peReader.PEHeaders.CorHeader.EntryPointTokenOrRelativeVirtualAddress; var mdReader = peReader.GetMetadataReader(); var methodDef = mdReader.GetMethodDefinition((MethodDefinitionHandle)MetadataTokens.Handle(peEntryPointToken)); Assert.Equal("Main", mdReader.GetString(methodDef.Name)); } [Fact] public void CustomDebugEntryPoint_Errors() { var source1 = @"class C { static void F() { } } class D<T> { static void G<S>() {} }"; var source2 = @"class C { static void F() { } }"; var c1 = CreateCompilation(source1, options: TestOptions.DebugDll); var c2 = CreateCompilation(source2, options: TestOptions.DebugDll); var f1 = c1.GetMember<MethodSymbol>("C.F"); var f2 = c2.GetMember<MethodSymbol>("C.F"); var g = c1.GetMember<MethodSymbol>("D.G"); var d = c1.GetMember<NamedTypeSymbol>("D"); Assert.NotNull(f1); Assert.NotNull(f2); Assert.NotNull(g); Assert.NotNull(d); var stInt = c1.GetSpecialType(SpecialType.System_Int32); var d_t_g_int = g.Construct(stInt); var d_int = d.Construct(stInt); var d_int_g = d_int.GetMember<MethodSymbol>("G"); var d_int_g_int = d_int_g.Construct(stInt); var result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: f2.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_t_g_int.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); result = c1.Emit(new MemoryStream(), new MemoryStream(), debugEntryPoint: d_int_g_int.GetPublicSymbol()); result.Diagnostics.Verify( // error CS8096: Debug entry point must be a definition of a source method in the current compilation. Diagnostic(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition)); } [Fact] [WorkItem(768862, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/768862")] public void TestLargeLineDelta() { var verbatim = string.Join("\r\n", Enumerable.Repeat("x", 1000)); var source = $@" class C {{ public static void Main() => System.Console.WriteLine(@""{verbatim}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""1001"" endColumn=""4"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.PortablePdb); // Native PDBs only support spans with line delta <= 127 (7 bit) // https://github.com/Microsoft/microsoft-pdb/blob/main/include/cvinfo.h#L4621 c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""40"" endLine=""129"" endColumn=""4"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); } [Fact] [WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")] public void TestLargeStartAndEndColumn_SameLine() { var spaces = new string(' ', 0x10000); var source = $@" class C {{ public static void Main() => {spaces}System.Console.WriteLine(""{spaces}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""65533"" endLine=""5"" endColumn=""65534"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] [WorkItem(20118, "https://github.com/dotnet/roslyn/issues/20118")] public void TestLargeStartAndEndColumn_DifferentLine() { var spaces = new string(' ', 0x10000); var source = $@" class C {{ public static void Main() => {spaces}System.Console.WriteLine( ""{spaces}""); }} "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""65534"" endLine=""6"" endColumn=""65534"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } #endregion #region Method Bodies [Fact] public void TestBasic() { var source = WithWindowsLineBreaks(@" class Program { Program() { } static void Main(string[] args) { Program p = new Program(); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Program"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <local name=""p"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestSimpleLocals() { var source = WithWindowsLineBreaks(@" class C { void Method() { //local at method scope object version = 6; System.Console.WriteLine(""version {0}"", version); { //a scope that defines no locals { //a nested local object foob = 1; System.Console.WriteLine(""foob {0}"", foob); } { //a nested local int foob1 = 1; System.Console.WriteLine(""foob1 {0}"", foob1); } System.Console.WriteLine(""Eva""); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Method", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Method""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""246"" /> <slot kind=""0"" offset=""402"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""28"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""58"" document=""1"" /> <entry offset=""0x14"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""12"" startColumn=""17"" endLine=""12"" endColumn=""33"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""60"" document=""1"" /> <entry offset=""0x29"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""14"" document=""1"" /> <entry offset=""0x2a"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""14"" document=""1"" /> <entry offset=""0x2b"" startLine=""17"" startColumn=""17"" endLine=""17"" endColumn=""31"" document=""1"" /> <entry offset=""0x2d"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""62"" document=""1"" /> <entry offset=""0x3e"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x3f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""45"" document=""1"" /> <entry offset=""0x4a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x4b"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4c""> <local name=""version"" il_index=""0"" il_start=""0x0"" il_end=""0x4c"" attributes=""0"" /> <scope startOffset=""0x15"" endOffset=""0x2a""> <local name=""foob"" il_index=""1"" il_start=""0x15"" il_end=""0x2a"" attributes=""0"" /> </scope> <scope startOffset=""0x2a"" endOffset=""0x3f""> <local name=""foob1"" il_index=""2"" il_start=""0x2a"" il_end=""0x3f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] [WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")] public void ConstructorsWithoutInitializers() { var source = WithWindowsLineBreaks( @"class C { C() { object o; } C(object x) { object y = x; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""3"" startColumn=""5"" endLine=""3"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""o"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""16"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <scope startOffset=""0x7"" endOffset=""0xb""> <local name=""y"" il_index=""0"" il_start=""0x7"" il_end=""0xb"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(7244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7244")] [Fact] public void ConstructorsWithInitializers() { var source = WithWindowsLineBreaks( @"class C { static object G = 1; object F = G; C() { object o; } C(object x) { object y = x; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" /> <entry offset=""0xb"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" /> <entry offset=""0x12"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x13"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <scope startOffset=""0x12"" endOffset=""0x14""> <local name=""o"" il_index=""0"" il_start=""0x12"" il_end=""0x14"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""18"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""16"" document=""1"" /> <entry offset=""0x12"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x13"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <scope startOffset=""0x12"" endOffset=""0x16""> <local name=""y"" il_index=""0"" il_start=""0x12"" il_end=""0x16"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } /// <summary> /// Although the debugging info attached to DebuggerHidden method is not used by the debugger /// (the debugger doesn't ever stop in the method) Dev11 emits the info and so do we. /// /// StepThrough method needs the information if JustMyCode is disabled and a breakpoint is set within the method. /// NonUserCode method needs the information if JustMyCode is disabled. /// /// It's up to the tool that consumes the debugging information, not the compiler to decide whether to ignore the info or not. /// BTW, the information can actually be retrieved at runtime from the PDB file via Reflection StackTrace. /// </summary> [Fact] public void MethodsWithDebuggerAttributes() { var source = WithWindowsLineBreaks(@" using System; using System.Diagnostics; class Program { [DebuggerHidden] static void Hidden() { int x = 1; Console.WriteLine(x); } [DebuggerStepThrough] static void StepThrough() { int y = 1; Console.WriteLine(y); } [DebuggerNonUserCode] static void NonUserCode() { int z = 1; Console.WriteLine(z); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Hidden""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </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=""0x3"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <namespace name=""System"" /> <namespace name=""System.Diagnostics"" /> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> <method containingType=""Program"" name=""StepThrough""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Hidden"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""y"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> <method containingType=""Program"" name=""NonUserCode""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Hidden"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""30"" document=""1"" /> <entry offset=""0xa"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } /// <summary> /// If a synthesized method contains any user code, /// the method must have a sequence point at /// offset 0 for correct stepping behavior. /// </summary> [WorkItem(804681, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/804681")] [Fact] public void SequencePointAtOffset0() { string source = WithWindowsLineBreaks( @"using System; class C { static Func<object, int> F = x => { Func<object, int> f = o => 1; Func<Func<object, int>, Func<object, int>> g = h => y => h(y); return g(f)(null); }; }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".cctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-45"" /> <lambda offset=""-147"" /> <lambda offset=""-109"" /> <lambda offset=""-45"" /> <lambda offset=""-40"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""9"" endColumn=""7"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <namespace name=""System"" /> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass2_0"" name=""&lt;.cctor&gt;b__3"" parameterNames=""y""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""66"" endLine=""7"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_0"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""-118"" /> <slot kind=""0"" offset=""-54"" /> <slot kind=""21"" offset=""-147"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x21"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""71"" document=""1"" /> <entry offset=""0x41"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x51"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x53""> <local name=""f"" il_index=""0"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> <local name=""g"" il_index=""1"" il_start=""0x0"" il_end=""0x53"" attributes=""0"" /> </scope> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_1"" parameterNames=""o""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""36"" endLine=""6"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.cctor&gt;b__2_2"" parameterNames=""h""> <customDebugInfo> <forward declaringType=""C"" methodName="".cctor"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-45"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""7"" startColumn=""61"" endLine=""7"" endColumn=""70"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Leading trivia is not included in the syntax offset. /// </summary> [Fact] public void SyntaxOffsetInPresenceOfTrivia_Methods() { string source = @" class C { public static void Main1() /*Comment1*/{/*Comment2*/int a = 1;/*Comment3*/}/*Comment4*/ public static void Main2() {/*Comment2*/int a = 2;/*Comment3*/}/*Comment4*/ }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // verify that both syntax offsets are the same c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main1""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""44"" endLine=""4"" endColumn=""45"" document=""1"" /> <entry offset=""0x1"" startLine=""4"" startColumn=""57"" endLine=""4"" endColumn=""67"" document=""1"" /> <entry offset=""0x3"" startLine=""4"" startColumn=""79"" endLine=""4"" endColumn=""80"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""C"" name=""Main2""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""45"" endLine=""5"" endColumn=""55"" document=""1"" /> <entry offset=""0x3"" startLine=""5"" startColumn=""67"" endLine=""5"" endColumn=""68"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } /// <summary> /// Leading and trailing trivia are not included in the syntax offset. /// </summary> [Fact] public void SyntaxOffsetInPresenceOfTrivia_Initializers() { string source = @" using System; class C1 { public static Func<int> e=() => 0; public static Func<int> f/*Comment0*/=/*Comment1*/() => 1;/*Comment2*/ public static Func<int> g=() => 2; } class C2 { public static Func<int> e=() => 0; public static Func<int> f=/*Comment1*/() => 1; public static Func<int> g=() => 2; } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // verify that syntax offsets of both .cctor's are the same c.VerifyPdb("C1..cctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C1"" name="".cctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <lambda offset=""-29"" /> <lambda offset=""-9"" /> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""39"" document=""1"" /> <entry offset=""0x15"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""63"" document=""1"" /> <entry offset=""0x2a"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""39"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); c.VerifyPdb("C2..cctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C2"" name="".cctor""> <customDebugInfo> <forward declaringType=""C1"" methodName="".cctor"" /> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <lambda offset=""-29"" /> <lambda offset=""-9"" /> <lambda offset=""-1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""51"" document=""1"" /> <entry offset=""0x2a"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region ReturnStatement [Fact] public void Return_Method1() { var source = WithWindowsLineBreaks(@" class Program { static int Main() { return 1; } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); // In order to place a breakpoint on the closing brace we need to save the return expression value to // a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived. v.VerifyIL("Program.Main", @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0005 -IL_0005: ldloc.0 IL_0006: ret }", sequencePoints: "Program.Main"); v.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x5"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Property1() { var source = WithWindowsLineBreaks(@" class C { static int P { get { return 1; } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); // In order to place a breakpoint on the closing brace we need to save the return expression value to // a local and then load it again (since sequence point needs an empty stack). This variable has to be marked as long-lived. v.VerifyIL("C.P.get", @" { // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) -IL_0000: nop -IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: br.s IL_0005 -IL_0005: ldloc.0 IL_0006: ret }", sequencePoints: "C.get_P"); v.VerifyPdb("C.get_P", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""14"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""15"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x5"" startLine=""6"" startColumn=""25"" endLine=""6"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Void1() { var source = @" class Program { static void Main() { return; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 4 (0x4) .maxstack 0 -IL_0000: nop -IL_0001: br.s IL_0003 -IL_0003: ret }", sequencePoints: "Program.Main"); } [Fact] public void Return_ExpressionBodied1() { var source = @" class Program { static int Main() => 1; } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 2 (0x2) .maxstack 1 -IL_0000: ldc.i4.1 IL_0001: ret }", sequencePoints: "Program.Main"); } [Fact] public void Return_FromExceptionHandler1() { var source = WithWindowsLineBreaks(@" using System; class Program { static int Main() { try { Console.WriteLine(); return 1; } catch (Exception) { return 2; } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: call ""void System.Console.WriteLine()"" IL_0007: nop -IL_0008: ldc.i4.1 IL_0009: stloc.0 IL_000a: leave.s IL_0012 } catch System.Exception { -IL_000c: pop -IL_000d: nop -IL_000e: ldc.i4.2 IL_000f: stloc.0 IL_0010: leave.s IL_0012 } -IL_0012: ldloc.0 IL_0013: ret }", sequencePoints: "Program.Main"); v.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""22"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""26"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""22"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } #endregion #region IfStatement [Fact] public void IfStatement() { var source = WithWindowsLineBreaks(@" class C { void Method() { bool b = true; if (b) { string s = ""true""; System.Console.WriteLine(s); } else { string s = ""false""; int i = 1; while (i < 100) { int j = i, k = 1; System.Console.WriteLine(j); i = j + k; } i = i + 1; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Method", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Method""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""1"" offset=""38"" /> <slot kind=""0"" offset=""76"" /> <slot kind=""0"" offset=""188"" /> <slot kind=""0"" offset=""218"" /> <slot kind=""0"" offset=""292"" /> <slot kind=""0"" offset=""299"" /> <slot kind=""1"" offset=""240"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""32"" document=""1"" /> <entry offset=""0x20"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""23"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""1"" /> <entry offset=""0x26"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x2a"" startLine=""19"" startColumn=""28"" endLine=""19"" endColumn=""33"" document=""1"" /> <entry offset=""0x2d"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""45"" document=""1"" /> <entry offset=""0x35"" startLine=""21"" startColumn=""17"" endLine=""21"" endColumn=""27"" document=""1"" /> <entry offset=""0x3c"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""14"" document=""1"" /> <entry offset=""0x3d"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""28"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x49"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""23"" document=""1"" /> <entry offset=""0x4f"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> <entry offset=""0x50"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x51""> <local name=""b"" il_index=""0"" il_start=""0x0"" il_end=""0x51"" attributes=""0"" /> <scope startOffset=""0x8"" endOffset=""0x17""> <local name=""s"" il_index=""2"" il_start=""0x8"" il_end=""0x17"" attributes=""0"" /> </scope> <scope startOffset=""0x19"" endOffset=""0x50""> <local name=""s"" il_index=""3"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" /> <local name=""i"" il_index=""4"" il_start=""0x19"" il_end=""0x50"" attributes=""0"" /> <scope startOffset=""0x25"" endOffset=""0x3d""> <local name=""j"" il_index=""5"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" /> <local name=""k"" il_index=""6"" il_start=""0x25"" il_end=""0x3d"" attributes=""0"" /> </scope> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region WhileStatement [WorkItem(538299, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538299")] [Fact] public void WhileStatement() { var source = @"using System; public class SeqPointForWhile { public static void Main() { SeqPointForWhile obj = new SeqPointForWhile(); obj.While(234); } int field; public void While(int p) { while (p > 0) // SeqPt should be generated at the end of loop { p = (int)(p / 2); if (p > 100) { continue; } else if (p > 10) { int x = p; field = x; } else { int x = p; Console.WriteLine(x); break; } } field = -1; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); // Offset 0x01 should be: // <entry offset=""0x1"" hidden=""true"" document=""1"" /> // Move original offset 0x01 to 0x33 // <entry offset=""0x33"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" /> // // Note: 16707566 == 0x00FEEFEE c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""SeqPointForWhile"" methodName=""Main"" /> <methods> <method containingType=""SeqPointForWhile"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <namespace name=""System"" /> </scope> </method> <method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointForWhile"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0xc"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" /> <entry offset=""0x11"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x13"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""27"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""27"" document=""1"" /> <entry offset=""0x1d"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""38"" document=""1"" /> <entry offset=""0x22"" startLine=""31"" startColumn=""17"" endLine=""31"" endColumn=""23"" document=""1"" /> <entry offset=""0x24"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""22"" document=""1"" /> <entry offset=""0x28"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""20"" document=""1"" /> <entry offset=""0x2f"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x30""> <scope startOffset=""0x11"" endOffset=""0x1a""> <local name=""x"" il_index=""0"" il_start=""0x11"" il_end=""0x1a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region ForStatement [Fact] public void ForStatement1() { var source = WithWindowsLineBreaks(@" class C { static bool F(int i) { return true; } static void G(int i) { } static void M() { for (int i = 1; F(i); G(i)) { System.Console.WriteLine(1); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""i"" /> <encLocalSlotMap> <slot kind=""0"" offset=""20"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""41"" document=""1"" /> <entry offset=""0xd"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""9"" startColumn=""31"" endLine=""9"" endColumn=""35"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""29"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x20""> <scope startOffset=""0x1"" endOffset=""0x1f""> <local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x1f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void ForStatement2() { var source = @" class C { static void M() { for (;;) { System.Console.WriteLine(1); } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x3"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void ForStatement3() { var source = WithWindowsLineBreaks(@" class C { static void M() { int i = 0; for (;;i++) { System.Console.WriteLine(i); } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""41"" document=""1"" /> <entry offset=""0xd"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region ForEachStatement [Fact] public void ForEachStatement_String() { var source = @" public class C { public static void Main() { foreach (var c in ""hello"") { System.Console.WriteLine(c); } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) '"hello"' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) Hidden index increment. // 10) 'in' // 11) Close brace at end of method c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x1a"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x23"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ForEachStatement_Array() { var source = WithWindowsLineBreaks(@" public class C { public static void Main() { foreach (var x in new int[2]) { System.Console.WriteLine(x); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new int[2]' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) Hidden index increment. // 10) 'in' // 11) Close brace at end of method c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""37"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x19"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""6"" startColumn=""24"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0x24"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x25""> <scope startOffset=""0xd"" endOffset=""0x1a""> <local name=""x"" il_index=""2"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")] [Fact] public void ForEachStatement_MultiDimensionalArray() { var source = @" public class C { public static void Main() { foreach (var x in new int[2, 3]) { System.Console.WriteLine(x); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new int[2, 3]' // 4) Hidden initial jump (of for loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) 'in' // 10) Close brace at end of method v.VerifyIL("C.Main", @" { // Code size 88 (0x58) .maxstack 3 .locals init (int[,] V_0, int V_1, int V_2, int V_3, int V_4, int V_5) //x -IL_0000: nop -IL_0001: nop -IL_0002: ldc.i4.2 IL_0003: ldc.i4.3 IL_0004: newobj ""int[*,*]..ctor"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: ldc.i4.0 IL_000c: callvirt ""int System.Array.GetUpperBound(int)"" IL_0011: stloc.1 IL_0012: ldloc.0 IL_0013: ldc.i4.1 IL_0014: callvirt ""int System.Array.GetUpperBound(int)"" IL_0019: stloc.2 IL_001a: ldloc.0 IL_001b: ldc.i4.0 IL_001c: callvirt ""int System.Array.GetLowerBound(int)"" IL_0021: stloc.3 ~IL_0022: br.s IL_0053 IL_0024: ldloc.0 IL_0025: ldc.i4.1 IL_0026: callvirt ""int System.Array.GetLowerBound(int)"" IL_002b: stloc.s V_4 ~IL_002d: br.s IL_004a -IL_002f: ldloc.0 IL_0030: ldloc.3 IL_0031: ldloc.s V_4 IL_0033: call ""int[*,*].Get"" IL_0038: stloc.s V_5 -IL_003a: nop -IL_003b: ldloc.s V_5 IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: nop -IL_0043: nop ~IL_0044: ldloc.s V_4 IL_0046: ldc.i4.1 IL_0047: add IL_0048: stloc.s V_4 -IL_004a: ldloc.s V_4 IL_004c: ldloc.2 IL_004d: ble.s IL_002f ~IL_004f: ldloc.3 IL_0050: ldc.i4.1 IL_0051: add IL_0052: stloc.3 -IL_0053: ldloc.3 IL_0054: ldloc.1 IL_0055: ble.s IL_0024 -IL_0057: ret } ", sequencePoints: "C.Main"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInAsyncMethod() { var source = WithWindowsLineBreaks(@" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console .WriteLine(); } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 81 (0x51) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 // sequence point: Console ... .WriteLine() IL_001c: call ""void System.Console.WriteLine()"" IL_0021: nop // sequence point: <hidden> IL_0022: leave.s IL_003c } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0024: stloc.2 IL_0025: ldarg.0 IL_0026: ldc.i4.s -2 IL_0028: stfld ""int Program.<Test>d__0.<>1__state"" IL_002d: ldarg.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0033: ldloc.2 IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0039: nop IL_003a: leave.s IL_0050 } // sequence point: } IL_003c: ldarg.0 IL_003d: ldc.i4.s -2 IL_003f: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_004f: nop IL_0050: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <forwardIterator name=""&lt;Test&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program+&lt;Test&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x51"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""1"" offset=""33"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x51""> <namespace name=""System"" /> </scope> <asyncInfo> <catchHandler offset=""0x24"" /> <kickoffMethod declaringType=""Program"" methodName=""Test"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalBeforeLocalFunction() { var source = @" class C { void M() { int i = 0; if (i != 0) { return; } string local() { throw null; } System.Console.Write(1); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.M", @" { // Code size 23 (0x17) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: if (i != 0) IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: cgt.un IL_0007: stloc.1 // sequence point: <hidden> IL_0008: ldloc.1 IL_0009: brfalse.s IL_000e // sequence point: { IL_000b: nop // sequence point: return; IL_000c: br.s IL_0016 // sequence point: <hidden> IL_000e: nop // sequence point: System.Console.Write(1); IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: nop // sequence point: } IL_0016: ret } ", sequencePoints: "C.M", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInAsyncMethodWithExplicitReturn() { var source = @" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console .WriteLine(); return; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 81 (0x51) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0022 // sequence point: Console ... .WriteLine() IL_001c: call ""void System.Console.WriteLine()"" IL_0021: nop // sequence point: return; IL_0022: leave.s IL_003c } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0024: stloc.2 IL_0025: ldarg.0 IL_0026: ldc.i4.s -2 IL_0028: stfld ""int Program.<Test>d__0.<>1__state"" IL_002d: ldarg.0 IL_002e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0033: ldloc.2 IL_0034: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0039: nop IL_003a: leave.s IL_0050 } // sequence point: } IL_003c: ldarg.0 IL_003d: ldc.i4.s -2 IL_003f: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0044: ldarg.0 IL_0045: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004a: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_004f: nop IL_0050: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInSimpleMethod() { var source = @" using System; class Program { public static void Test() { int i = 0; if (i != 0) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Test()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop // sequence point: int i = 0; IL_0001: ldc.i4.0 IL_0002: stloc.0 // sequence point: if (i != 0) IL_0003: ldloc.0 IL_0004: ldc.i4.0 IL_0005: cgt.un IL_0007: stloc.1 // sequence point: <hidden> IL_0008: ldloc.1 IL_0009: brfalse.s IL_0011 // sequence point: Console.WriteLine(); IL_000b: call ""void System.Console.WriteLine()"" IL_0010: nop // sequence point: } IL_0011: ret } ", sequencePoints: "Program.Test", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ElseConditionalInAsyncMethod() { var source = WithWindowsLineBreaks(@" using System; class Program { public static async void Test() { int i = 0; if (i != 0) Console.WriteLine(""one""); else Console.WriteLine(""other""); } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 99 (0x63) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: if (i != 0) IL_000f: ldarg.0 IL_0010: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0015: ldc.i4.0 IL_0016: cgt.un IL_0018: stloc.1 // sequence point: <hidden> IL_0019: ldloc.1 IL_001a: brfalse.s IL_0029 // sequence point: Console.WriteLine(""one""); IL_001c: ldstr ""one"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: nop // sequence point: <hidden> IL_0027: br.s IL_0034 // sequence point: Console.WriteLine(""other""); IL_0029: ldstr ""other"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: nop // sequence point: <hidden> IL_0034: leave.s IL_004e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0036: stloc.2 IL_0037: ldarg.0 IL_0038: ldc.i4.s -2 IL_003a: stfld ""int Program.<Test>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0045: ldloc.2 IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_004b: nop IL_004c: leave.s IL_0062 } // sequence point: } IL_004e: ldarg.0 IL_004f: ldc.i4.s -2 IL_0051: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0061: nop IL_0062: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <forwardIterator name=""&lt;Test&gt;d__0"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> </method> <method containingType=""Program+&lt;Test&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x63"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""1"" offset=""33"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""20"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""38"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""40"" document=""1"" /> <entry offset=""0x34"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x63""> <namespace name=""System"" /> </scope> <asyncInfo> <catchHandler offset=""0x36"" /> <kickoffMethod declaringType=""Program"" methodName=""Test"" /> </asyncInfo> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ConditionalInTry() { var source = WithWindowsLineBreaks(@" using System; class Program { public static void Test() { try { int i = 0; if (i != 0) Console.WriteLine(); } catch { } } } "); var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Test", @" { // Code size 27 (0x1b) .maxstack 2 .locals init (int V_0, //i bool V_1) // sequence point: { IL_0000: nop .try { // sequence point: { IL_0001: nop // sequence point: int i = 0; IL_0002: ldc.i4.0 IL_0003: stloc.0 // sequence point: if (i != 0) IL_0004: ldloc.0 IL_0005: ldc.i4.0 IL_0006: cgt.un IL_0008: stloc.1 // sequence point: <hidden> IL_0009: ldloc.1 IL_000a: brfalse.s IL_0012 // sequence point: Console.WriteLine(); IL_000c: call ""void System.Console.WriteLine()"" IL_0011: nop // sequence point: } IL_0012: nop IL_0013: leave.s IL_001a } catch object { // sequence point: catch IL_0015: pop // sequence point: { IL_0016: nop // sequence point: } IL_0017: nop IL_0018: leave.s IL_001a } // sequence point: } IL_001a: ret } ", sequencePoints: "Program.Test", source: source); v.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Test""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""43"" /> <slot kind=""1"" offset=""65"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x4"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""17"" endLine=""13"" endColumn=""37"" document=""1"" /> <entry offset=""0x12"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x15"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""14"" document=""1"" /> <entry offset=""0x16"" startLine=""15"" startColumn=""15"" endLine=""15"" endColumn=""16"" document=""1"" /> <entry offset=""0x17"" startLine=""15"" startColumn=""17"" endLine=""15"" endColumn=""18"" document=""1"" /> <entry offset=""0x1a"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x13""> <local name=""i"" il_index=""0"" il_start=""0x1"" il_end=""0x13"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(544937, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544937")] [Fact] public void ForEachStatement_MultiDimensionalArrayBreakAndContinue() { var source = @" using System; class C { static void Main() { int[, ,] array = new[,,] { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} }, }; foreach (int i in array) { if (i % 2 == 1) continue; if (i > 4) break; Console.WriteLine(i); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll.WithModuleName("MODULE")); // Stepping: // After "continue", step to "in". // After "break", step to first sequence point following loop body (in this case, method close brace). v.VerifyIL("C.Main", @" { // Code size 169 (0xa9) .maxstack 4 .locals init (int[,,] V_0, //array int[,,] V_1, int V_2, int V_3, int V_4, int V_5, int V_6, int V_7, int V_8, //i bool V_9, bool V_10) -IL_0000: nop -IL_0001: ldc.i4.2 IL_0002: ldc.i4.2 IL_0003: ldc.i4.2 IL_0004: newobj ""int[*,*,*]..ctor"" IL_0009: dup IL_000a: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=32 <PrivateImplementationDetails>.8B4B2444E57AED8C2D05A1293255DA1B048C63224317D4666230760935FA4A18"" IL_000f: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0014: stloc.0 -IL_0015: nop -IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: ldloc.1 IL_0019: ldc.i4.0 IL_001a: callvirt ""int System.Array.GetUpperBound(int)"" IL_001f: stloc.2 IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: callvirt ""int System.Array.GetUpperBound(int)"" IL_0027: stloc.3 IL_0028: ldloc.1 IL_0029: ldc.i4.2 IL_002a: callvirt ""int System.Array.GetUpperBound(int)"" IL_002f: stloc.s V_4 IL_0031: ldloc.1 IL_0032: ldc.i4.0 IL_0033: callvirt ""int System.Array.GetLowerBound(int)"" IL_0038: stloc.s V_5 ~IL_003a: br.s IL_00a3 IL_003c: ldloc.1 IL_003d: ldc.i4.1 IL_003e: callvirt ""int System.Array.GetLowerBound(int)"" IL_0043: stloc.s V_6 ~IL_0045: br.s IL_0098 IL_0047: ldloc.1 IL_0048: ldc.i4.2 IL_0049: callvirt ""int System.Array.GetLowerBound(int)"" IL_004e: stloc.s V_7 ~IL_0050: br.s IL_008c -IL_0052: ldloc.1 IL_0053: ldloc.s V_5 IL_0055: ldloc.s V_6 IL_0057: ldloc.s V_7 IL_0059: call ""int[*,*,*].Get"" IL_005e: stloc.s V_8 -IL_0060: nop -IL_0061: ldloc.s V_8 IL_0063: ldc.i4.2 IL_0064: rem IL_0065: ldc.i4.1 IL_0066: ceq IL_0068: stloc.s V_9 ~IL_006a: ldloc.s V_9 IL_006c: brfalse.s IL_0070 -IL_006e: br.s IL_0086 -IL_0070: ldloc.s V_8 IL_0072: ldc.i4.4 IL_0073: cgt IL_0075: stloc.s V_10 ~IL_0077: ldloc.s V_10 IL_0079: brfalse.s IL_007d -IL_007b: br.s IL_00a8 -IL_007d: ldloc.s V_8 IL_007f: call ""void System.Console.WriteLine(int)"" IL_0084: nop -IL_0085: nop ~IL_0086: ldloc.s V_7 IL_0088: ldc.i4.1 IL_0089: add IL_008a: stloc.s V_7 -IL_008c: ldloc.s V_7 IL_008e: ldloc.s V_4 IL_0090: ble.s IL_0052 ~IL_0092: ldloc.s V_6 IL_0094: ldc.i4.1 IL_0095: add IL_0096: stloc.s V_6 -IL_0098: ldloc.s V_6 IL_009a: ldloc.3 IL_009b: ble.s IL_0047 ~IL_009d: ldloc.s V_5 IL_009f: ldc.i4.1 IL_00a0: add IL_00a1: stloc.s V_5 -IL_00a3: ldloc.s V_5 IL_00a5: ldloc.2 IL_00a6: ble.s IL_003c -IL_00a8: ret } ", sequencePoints: "C.Main"); } [Fact] public void ForEachStatement_Enumerator() { var source = @" public class C { public static void Main() { foreach (var x in new System.Collections.Generic.List<int>()) { System.Console.WriteLine(x); } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); // Sequence points: // 1) Open brace at start of method // 2) 'foreach' // 3) 'new System.Collections.Generic.List<int>()' // 4) Hidden initial jump (of while loop) // 5) 'var c' // 6) Open brace of loop // 7) Loop body // 8) Close brace of loop // 9) 'in' // 10) hidden point in Finally // 11) Close brace at end of method v.VerifyIL("C.Main", @" { // Code size 59 (0x3b) .maxstack 1 .locals init (System.Collections.Generic.List<int>.Enumerator V_0, int V_1) //x -IL_0000: nop -IL_0001: nop -IL_0002: newobj ""System.Collections.Generic.List<int>..ctor()"" IL_0007: call ""System.Collections.Generic.List<int>.Enumerator System.Collections.Generic.List<int>.GetEnumerator()"" IL_000c: stloc.0 .try { ~IL_000d: br.s IL_0020 -IL_000f: ldloca.s V_0 IL_0011: call ""int System.Collections.Generic.List<int>.Enumerator.Current.get"" IL_0016: stloc.1 -IL_0017: nop -IL_0018: ldloc.1 IL_0019: call ""void System.Console.WriteLine(int)"" IL_001e: nop -IL_001f: nop -IL_0020: ldloca.s V_0 IL_0022: call ""bool System.Collections.Generic.List<int>.Enumerator.MoveNext()"" IL_0027: brtrue.s IL_000f IL_0029: leave.s IL_003a } finally { ~IL_002b: ldloca.s V_0 IL_002d: constrained. ""System.Collections.Generic.List<int>.Enumerator"" IL_0033: callvirt ""void System.IDisposable.Dispose()"" IL_0038: nop IL_0039: endfinally } -IL_003a: ret } ", sequencePoints: "C.Main"); } [WorkItem(718501, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718501")] [Fact] public void ForEachNops() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { foreach (var i in l.AsEnumerable()) { switch (i.Count) { case 1: break; default: if (i.Count != 0) { } break; } } } } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <encLocalSlotMap> <slot kind=""5"" offset=""15"" /> <slot kind=""0"" offset=""15"" /> <slot kind=""35"" offset=""83"" /> <slot kind=""1"" offset=""83"" /> <slot kind=""1"" offset=""237"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""20"" document=""1"" /> <entry offset=""0x2"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""47"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""12"" startColumn=""22"" endLine=""12"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""14"" document=""1"" /> <entry offset=""0x1c"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" startLine=""17"" startColumn=""25"" endLine=""17"" endColumn=""31"" document=""1"" /> <entry offset=""0x2d"" startLine=""20"" startColumn=""25"" endLine=""20"" endColumn=""42"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""21"" startColumn=""25"" endLine=""21"" endColumn=""26"" document=""1"" /> <entry offset=""0x3d"" startLine=""22"" startColumn=""25"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x3e"" startLine=""24"" startColumn=""25"" endLine=""24"" endColumn=""31"" document=""1"" /> <entry offset=""0x40"" startLine=""26"" startColumn=""13"" endLine=""26"" endColumn=""14"" document=""1"" /> <entry offset=""0x41"" startLine=""12"" startColumn=""28"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x4b"" hidden=""true"" document=""1"" /> <entry offset=""0x55"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x57""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <scope startOffset=""0x14"" endOffset=""0x41""> <local name=""i"" il_index=""1"" il_start=""0x14"" il_end=""0x41"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>" ); } [Fact] public void ForEachStatement_Deconstruction() { var source = WithWindowsLineBreaks(@" public class C { public static (int, (bool, double))[] F() => new[] { (1, (true, 2.0)) }; public static void Main() { foreach (var (c, (d, e)) in F()) { System.Console.WriteLine(c); } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", @" { // Code size 70 (0x46) .maxstack 2 .locals init (System.ValueTuple<int, System.ValueTuple<bool, double>>[] V_0, int V_1, int V_2, //c bool V_3, //d double V_4, //e System.ValueTuple<bool, double> V_5) // sequence point: { IL_0000: nop // sequence point: foreach IL_0001: nop // sequence point: F() IL_0002: call ""System.ValueTuple<int, System.ValueTuple<bool, double>>[] C.F()"" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 // sequence point: <hidden> IL_000a: br.s IL_003f // sequence point: var (c, (d, e)) IL_000c: ldloc.0 IL_000d: ldloc.1 IL_000e: ldelem ""System.ValueTuple<int, System.ValueTuple<bool, double>>"" IL_0013: dup IL_0014: ldfld ""System.ValueTuple<bool, double> System.ValueTuple<int, System.ValueTuple<bool, double>>.Item2"" IL_0019: stloc.s V_5 IL_001b: ldfld ""int System.ValueTuple<int, System.ValueTuple<bool, double>>.Item1"" IL_0020: stloc.2 IL_0021: ldloc.s V_5 IL_0023: ldfld ""bool System.ValueTuple<bool, double>.Item1"" IL_0028: stloc.3 IL_0029: ldloc.s V_5 IL_002b: ldfld ""double System.ValueTuple<bool, double>.Item2"" IL_0030: stloc.s V_4 // sequence point: { IL_0032: nop // sequence point: System.Console.WriteLine(c); IL_0033: ldloc.2 IL_0034: call ""void System.Console.WriteLine(int)"" IL_0039: nop // sequence point: } IL_003a: nop // sequence point: <hidden> IL_003b: ldloc.1 IL_003c: ldc.i4.1 IL_003d: add IL_003e: stloc.1 // sequence point: in IL_003f: ldloc.1 IL_0040: ldloc.0 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_000c // sequence point: } IL_0045: ret } ", sequencePoints: "C.Main", source: source); v.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""50"" endLine=""4"" endColumn=""76"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" /> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""25"" /> <slot kind=""0"" offset=""29"" /> <slot kind=""0"" offset=""32"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""37"" endLine=""8"" endColumn=""40"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x32"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x33"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""41"" document=""1"" /> <entry offset=""0x3a"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""8"" startColumn=""34"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x45"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x46""> <scope startOffset=""0xc"" endOffset=""0x3b""> <local name=""c"" il_index=""2"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> <local name=""d"" il_index=""3"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> <local name=""e"" il_index=""4"" il_start=""0xc"" il_end=""0x3b"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region Switch [Fact] public void SwitchWithPattern_01() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static string Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""0"" offset=""59"" /> <slot kind=""0"" offset=""163"" /> <slot kind=""0"" offset=""250"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x2e"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""57"" document=""1"" /> <entry offset=""0x4f"" hidden=""true"" document=""1"" /> <entry offset=""0x53"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""57"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""59"" document=""1"" /> <entry offset=""0x93"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""43"" document=""1"" /> <entry offset=""0xa7"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xaa""> <scope startOffset=""0x1d"" endOffset=""0x4f""> <local name=""s"" il_index=""0"" il_start=""0x1d"" il_end=""0x4f"" attributes=""0"" /> </scope> <scope startOffset=""0x4f"" endOffset=""0x72""> <local name=""s"" il_index=""1"" il_start=""0x4f"" il_end=""0x72"" attributes=""0"" /> </scope> <scope startOffset=""0x72"" endOffset=""0x93""> <local name=""t"" il_index=""2"" il_start=""0x72"" il_end=""0x93"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchWithPattern_02() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static System.Func<string> Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: return () => $""Student {s.Name} ({s.GPA:N1})""; case Student s: return () => $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return () => $""Teacher {t.Name} of {t.Subject}""; default: return () => $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""109"" closure=""1"" /> <lambda offset=""202"" closure=""1"" /> <lambda offset=""295"" closure=""1"" /> <lambda offset=""383"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x5f"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""63"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""63"" document=""1"" /> <entry offset=""0x8d"" hidden=""true"" document=""1"" /> <entry offset=""0x8f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""65"" document=""1"" /> <entry offset=""0x9f"" startLine=""29"" startColumn=""17"" endLine=""29"" endColumn=""49"" document=""1"" /> <entry offset=""0xaf"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb2""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb2"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xaf""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xaf"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void SwitchWithPatternAndLocalFunctions() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Program { private static List<List<int>> l = new List<List<int>>(); static void Main(string[] args) { Student s = new Student(); s.Name = ""Bozo""; s.GPA = 2.3; Operate(s); } static System.Func<string> Operate(Person p) { switch (p) { case Student s when s.GPA > 3.5: string f1() => $""Student {s.Name} ({s.GPA:N1})""; return f1; case Student s: string f2() => $""Student {s.Name} ({s.GPA:N1})""; return f2; case Teacher t: string f3() => $""Teacher {t.Name} of {t.Subject}""; return f3; default: string f4() => $""Person {p.Name}""; return f4; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } "); // we just want this to compile without crashing/asserting var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Program.Operate", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Operate"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""30"" offset=""11"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""0"" /> <closure offset=""11"" /> <lambda offset=""111"" closure=""1"" /> <lambda offset=""234"" closure=""1"" /> <lambda offset=""357"" closure=""1"" /> <lambda offset=""475"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0xe"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""22"" startColumn=""28"" endLine=""22"" endColumn=""44"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x60"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""27"" startColumn=""17"" endLine=""27"" endColumn=""27"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""27"" document=""1"" /> <entry offset=""0xa2"" hidden=""true"" document=""1"" /> <entry offset=""0xa3"" startLine=""33"" startColumn=""17"" endLine=""33"" endColumn=""27"" document=""1"" /> <entry offset=""0xb3"" startLine=""35"" startColumn=""5"" endLine=""35"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb6""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xb6"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0xb3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0xe"" il_end=""0xb3"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17090, "https://github.com/dotnet/roslyn/issues/17090"), WorkItem(19731, "https://github.com/dotnet/roslyn/issues/19731")] [Fact] public void SwitchWithConstantPattern() { string source = @" using System; class Program { static void Main(string[] args) { M1(); M2(); } static void M1() { switch (1) { case 0 when true: ; case 1: Console.Write(1); break; case 2: ; } } static void M2() { switch (nameof(M2)) { case nameof(M1) when true: ; case nameof(M2): Console.Write(nameof(M2)); break; case nameof(Main): ; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "1M2"); verifier.VerifyIL(qualifiedMethodName: "Program.M1", sequencePoints: "Program.M1", source: source, expectedIL: @"{ // Code size 17 (0x11) .maxstack 1 .locals init (int V_0, int V_1) // sequence point: { IL_0000: nop // sequence point: switch ... (1 IL_0001: ldc.i4.1 IL_0002: stloc.1 IL_0003: ldc.i4.1 IL_0004: stloc.0 // sequence point: <hidden> IL_0005: br.s IL_0007 // sequence point: Console.Write(1); IL_0007: ldc.i4.1 IL_0008: call ""void System.Console.Write(int)"" IL_000d: nop // sequence point: break; IL_000e: br.s IL_0010 // sequence point: } IL_0010: ret }"); verifier.VerifyIL(qualifiedMethodName: "Program.M2", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (string V_0, string V_1) // sequence point: { IL_0000: nop // sequence point: switch ... (nameof(M2) IL_0001: ldstr ""M2"" IL_0006: stloc.1 IL_0007: ldstr ""M2"" IL_000c: stloc.0 // sequence point: <hidden> IL_000d: br.s IL_000f // sequence point: Console.Write(nameof(M2)); IL_000f: ldstr ""M2"" IL_0014: call ""void System.Console.Write(string)"" IL_0019: nop // sequence point: break; IL_001a: br.s IL_001c // sequence point: } IL_001c: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "1M2"); verifier.VerifyIL("Program.M1", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ret }"); verifier.VerifyIL("Program.M2", @"{ // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""M2"" IL_0005: call ""void System.Console.Write(string)"" IL_000a: ret }"); } [WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")] [Fact] public void SwitchWithConstantGenericPattern_01() { string source = @" using System; class Program { static void Main(string[] args) { M1<int>(); // 1 M1<long>(); // 2 M2<string>(); // 3 M2<int>(); // 4 } static void M1<T>() { switch (1) { case T t: Console.Write(1); break; case int i: Console.Write(2); break; } } static void M2<T>() { switch (nameof(M2)) { case T t: Console.Write(3); break; case string s: Console.Write(4); break; case null: ; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "1234"); verifier.VerifyIL(qualifiedMethodName: "Program.M1<T>", sequencePoints: "Program.M1", source: source, expectedIL: @"{ // Code size 60 (0x3c) .maxstack 1 .locals init (T V_0, //t int V_1, //i int V_2) // sequence point: { IL_0000: nop // sequence point: switch (1) IL_0001: ldc.i4.1 IL_0002: stloc.2 IL_0003: ldc.i4.1 IL_0004: stloc.1 // sequence point: <hidden> IL_0005: ldloc.1 IL_0006: box ""int"" IL_000b: isinst ""T"" IL_0010: brfalse.s IL_0030 IL_0012: ldloc.1 IL_0013: box ""int"" IL_0018: isinst ""T"" IL_001d: unbox.any ""T"" IL_0022: stloc.0 // sequence point: <hidden> IL_0023: br.s IL_0025 // sequence point: <hidden> IL_0025: br.s IL_0027 // sequence point: Console.Write(1); IL_0027: ldc.i4.1 IL_0028: call ""void System.Console.Write(int)"" IL_002d: nop // sequence point: break; IL_002e: br.s IL_003b // sequence point: <hidden> IL_0030: br.s IL_0032 // sequence point: Console.Write(2); IL_0032: ldc.i4.2 IL_0033: call ""void System.Console.Write(int)"" IL_0038: nop // sequence point: break; IL_0039: br.s IL_003b // sequence point: } IL_003b: ret }"); verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 58 (0x3a) .maxstack 1 .locals init (T V_0, //t string V_1, //s string V_2) // sequence point: { IL_0000: nop // sequence point: switch (nameof(M2)) IL_0001: ldstr ""M2"" IL_0006: stloc.2 IL_0007: ldstr ""M2"" IL_000c: stloc.1 // sequence point: <hidden> IL_000d: ldloc.1 IL_000e: isinst ""T"" IL_0013: brfalse.s IL_002e IL_0015: ldloc.1 IL_0016: isinst ""T"" IL_001b: unbox.any ""T"" IL_0020: stloc.0 // sequence point: <hidden> IL_0021: br.s IL_0023 // sequence point: <hidden> IL_0023: br.s IL_0025 // sequence point: Console.Write(3); IL_0025: ldc.i4.3 IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop // sequence point: break; IL_002c: br.s IL_0039 // sequence point: <hidden> IL_002e: br.s IL_0030 // sequence point: Console.Write(4); IL_0030: ldc.i4.4 IL_0031: call ""void System.Console.Write(int)"" IL_0036: nop // sequence point: break; IL_0037: br.s IL_0039 // sequence point: } IL_0039: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "1234"); verifier.VerifyIL("Program.M1<T>", @"{ // Code size 29 (0x1d) .maxstack 1 .locals init (int V_0) //i IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box ""int"" IL_0008: isinst ""T"" IL_000d: brfalse.s IL_0016 IL_000f: ldc.i4.1 IL_0010: call ""void System.Console.Write(int)"" IL_0015: ret IL_0016: ldc.i4.2 IL_0017: call ""void System.Console.Write(int)"" IL_001c: ret }"); verifier.VerifyIL("Program.M2<T>", @"{ // Code size 28 (0x1c) .maxstack 1 .locals init (string V_0) //s IL_0000: ldstr ""M2"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: isinst ""T"" IL_000c: brfalse.s IL_0015 IL_000e: ldc.i4.3 IL_000f: call ""void System.Console.Write(int)"" IL_0014: ret IL_0015: ldc.i4.4 IL_0016: call ""void System.Console.Write(int)"" IL_001b: ret }"); } [WorkItem(19734, "https://github.com/dotnet/roslyn/issues/19734")] [Fact] public void SwitchWithConstantGenericPattern_02() { string source = @" using System; class Program { static void Main(string[] args) { M2<string>(); // 6 M2<int>(); // 6 } static void M2<T>() { const string x = null; switch (x) { case T t: ; case string s: ; case null: Console.Write(6); break; } } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, expectedOutput: "66"); verifier.VerifyIL(qualifiedMethodName: "Program.M2<T>", sequencePoints: "Program.M2", source: source, expectedIL: @"{ // Code size 17 (0x11) .maxstack 1 .locals init (T V_0, //t string V_1, //s string V_2, string V_3) // sequence point: { IL_0000: nop // sequence point: switch (x) IL_0001: ldnull IL_0002: stloc.3 IL_0003: ldnull IL_0004: stloc.2 // sequence point: <hidden> IL_0005: br.s IL_0007 // sequence point: Console.Write(6); IL_0007: ldc.i4.6 IL_0008: call ""void System.Console.Write(int)"" IL_000d: nop // sequence point: break; IL_000e: br.s IL_0010 // sequence point: } IL_0010: ret }"); // Check the release code generation too. c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); c.VerifyDiagnostics(); verifier = CompileAndVerify(c, expectedOutput: "66"); verifier.VerifyIL("Program.M2<T>", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldc.i4.6 IL_0001: call ""void System.Console.Write(int)"" IL_0006: ret }"); } [Fact] [WorkItem(31665, "https://github.com/dotnet/roslyn/issues/31665")] public void TestSequencePoints_31665() { var source = @" using System; internal class Program { private static void Main(string[] args) { var s = ""1""; if (true) switch (s) { case ""1"": Console.Out.WriteLine(""Input was 1""); break; default: throw new Exception(""Default case""); } else Console.Out.WriteLine(""Too many inputs""); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.Main(string[])", @" { // Code size 60 (0x3c) .maxstack 2 .locals init (string V_0, //s bool V_1, string V_2, string V_3) // sequence point: { IL_0000: nop // sequence point: var s = ""1""; IL_0001: ldstr ""1"" IL_0006: stloc.0 // sequence point: if (true) IL_0007: ldc.i4.1 IL_0008: stloc.1 // sequence point: switch (s) IL_0009: ldloc.0 IL_000a: stloc.3 // sequence point: <hidden> IL_000b: ldloc.3 IL_000c: stloc.2 // sequence point: <hidden> IL_000d: ldloc.2 IL_000e: ldstr ""1"" IL_0013: call ""bool string.op_Equality(string, string)"" IL_0018: brtrue.s IL_001c IL_001a: br.s IL_002e // sequence point: Console.Out.WriteLine(""Input was 1""); IL_001c: call ""System.IO.TextWriter System.Console.Out.get"" IL_0021: ldstr ""Input was 1"" IL_0026: callvirt ""void System.IO.TextWriter.WriteLine(string)"" IL_002b: nop // sequence point: break; IL_002c: br.s IL_0039 // sequence point: throw new Exception(""Default case""); IL_002e: ldstr ""Default case"" IL_0033: newobj ""System.Exception..ctor(string)"" IL_0038: throw // sequence point: <hidden> IL_0039: br.s IL_003b // sequence point: } IL_003b: ret } ", sequencePoints: "Program.Main", source: source); } [Fact] [WorkItem(17076, "https://github.com/dotnet/roslyn/issues/17076")] public void TestSequencePoints_17076() { var source = @" using System.Threading.Tasks; internal class Program { private static void Main(string[] args) { M(new Node()).GetAwaiter().GetResult(); } static async Task M(Node node) { while (node != null) { if (node is A a) { await Task.Yield(); return; } else if (node is B b) { await Task.Yield(); return; } node = node.Parent; } } } class Node { public Node Parent = null; } class A : Node { } class B : Node { } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 403 (0x193) .maxstack 3 .locals init (int V_0, bool V_1, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2, System.Runtime.CompilerServices.YieldAwaitable V_3, Program.<M>d__1 V_4, bool V_5, System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_6, bool V_7, System.Exception V_8) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0012 IL_000a: br.s IL_000c IL_000c: ldloc.0 IL_000d: ldc.i4.1 IL_000e: beq.s IL_0014 IL_0010: br.s IL_0019 IL_0012: br.s IL_007e IL_0014: br IL_0109 // sequence point: { IL_0019: nop // sequence point: <hidden> IL_001a: br IL_0150 // sequence point: { IL_001f: nop // sequence point: if (node is A a) IL_0020: ldarg.0 IL_0021: ldarg.0 IL_0022: ldfld ""Node Program.<M>d__1.node"" IL_0027: isinst ""A"" IL_002c: stfld ""A Program.<M>d__1.<a>5__1"" IL_0031: ldarg.0 IL_0032: ldfld ""A Program.<M>d__1.<a>5__1"" IL_0037: ldnull IL_0038: cgt.un IL_003a: stloc.1 // sequence point: <hidden> IL_003b: ldloc.1 IL_003c: brfalse.s IL_00a7 // sequence point: { IL_003e: nop // sequence point: await Task.Yield(); IL_003f: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_0044: stloc.3 IL_0045: ldloca.s V_3 IL_0047: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_004c: stloc.2 // sequence point: <hidden> IL_004d: ldloca.s V_2 IL_004f: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_0054: brtrue.s IL_009a IL_0056: ldarg.0 IL_0057: ldc.i4.0 IL_0058: dup IL_0059: stloc.0 IL_005a: stfld ""int Program.<M>d__1.<>1__state"" // async: yield IL_005f: ldarg.0 IL_0060: ldloc.2 IL_0061: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0066: ldarg.0 IL_0067: stloc.s V_4 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_006f: ldloca.s V_2 IL_0071: ldloca.s V_4 IL_0073: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)"" IL_0078: nop IL_0079: leave IL_0192 // async: resume IL_007e: ldarg.0 IL_007f: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0084: stloc.2 IL_0085: ldarg.0 IL_0086: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_008b: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_0091: ldarg.0 IL_0092: ldc.i4.m1 IL_0093: dup IL_0094: stloc.0 IL_0095: stfld ""int Program.<M>d__1.<>1__state"" IL_009a: ldloca.s V_2 IL_009c: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_00a1: nop // sequence point: return; IL_00a2: leave IL_017e // sequence point: if (node is B b) IL_00a7: ldarg.0 IL_00a8: ldarg.0 IL_00a9: ldfld ""Node Program.<M>d__1.node"" IL_00ae: isinst ""B"" IL_00b3: stfld ""B Program.<M>d__1.<b>5__2"" IL_00b8: ldarg.0 IL_00b9: ldfld ""B Program.<M>d__1.<b>5__2"" IL_00be: ldnull IL_00bf: cgt.un IL_00c1: stloc.s V_5 // sequence point: <hidden> IL_00c3: ldloc.s V_5 IL_00c5: brfalse.s IL_0130 // sequence point: { IL_00c7: nop // sequence point: await Task.Yield(); IL_00c8: call ""System.Runtime.CompilerServices.YieldAwaitable System.Threading.Tasks.Task.Yield()"" IL_00cd: stloc.3 IL_00ce: ldloca.s V_3 IL_00d0: call ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter()"" IL_00d5: stloc.s V_6 // sequence point: <hidden> IL_00d7: ldloca.s V_6 IL_00d9: call ""bool System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.IsCompleted.get"" IL_00de: brtrue.s IL_0126 IL_00e0: ldarg.0 IL_00e1: ldc.i4.1 IL_00e2: dup IL_00e3: stloc.0 IL_00e4: stfld ""int Program.<M>d__1.<>1__state"" // async: yield IL_00e9: ldarg.0 IL_00ea: ldloc.s V_6 IL_00ec: stfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_00f1: ldarg.0 IL_00f2: stloc.s V_4 IL_00f4: ldarg.0 IL_00f5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_00fa: ldloca.s V_6 IL_00fc: ldloca.s V_4 IL_00fe: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Program.<M>d__1>(ref System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ref Program.<M>d__1)"" IL_0103: nop IL_0104: leave IL_0192 // async: resume IL_0109: ldarg.0 IL_010a: ldfld ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_010f: stloc.s V_6 IL_0111: ldarg.0 IL_0112: ldflda ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter Program.<M>d__1.<>u__1"" IL_0117: initobj ""System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"" IL_011d: ldarg.0 IL_011e: ldc.i4.m1 IL_011f: dup IL_0120: stloc.0 IL_0121: stfld ""int Program.<M>d__1.<>1__state"" IL_0126: ldloca.s V_6 IL_0128: call ""void System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"" IL_012d: nop // sequence point: return; IL_012e: leave.s IL_017e // sequence point: <hidden> IL_0130: ldarg.0 IL_0131: ldnull IL_0132: stfld ""B Program.<M>d__1.<b>5__2"" // sequence point: node = node.Parent; IL_0137: ldarg.0 IL_0138: ldarg.0 IL_0139: ldfld ""Node Program.<M>d__1.node"" IL_013e: ldfld ""Node Node.Parent"" IL_0143: stfld ""Node Program.<M>d__1.node"" // sequence point: } IL_0148: nop IL_0149: ldarg.0 IL_014a: ldnull IL_014b: stfld ""A Program.<M>d__1.<a>5__1"" // sequence point: while (node != null) IL_0150: ldarg.0 IL_0151: ldfld ""Node Program.<M>d__1.node"" IL_0156: ldnull IL_0157: cgt.un IL_0159: stloc.s V_7 // sequence point: <hidden> IL_015b: ldloc.s V_7 IL_015d: brtrue IL_001f IL_0162: leave.s IL_017e } catch System.Exception { // sequence point: <hidden> IL_0164: stloc.s V_8 IL_0166: ldarg.0 IL_0167: ldc.i4.s -2 IL_0169: stfld ""int Program.<M>d__1.<>1__state"" IL_016e: ldarg.0 IL_016f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_0174: ldloc.s V_8 IL_0176: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_017b: nop IL_017c: leave.s IL_0192 } // sequence point: } IL_017e: ldarg.0 IL_017f: ldc.i4.s -2 IL_0181: stfld ""int Program.<M>d__1.<>1__state"" // sequence point: <hidden> IL_0186: ldarg.0 IL_0187: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Program.<M>d__1.<>t__builder"" IL_018c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0191: nop IL_0192: ret } ", sequencePoints: "Program+<M>d__1.MoveNext", source: source); } [Fact] [WorkItem(28288, "https://github.com/dotnet/roslyn/issues/28288")] public void TestSequencePoints_28288() { var source = @" using System.Threading.Tasks; public class C { public static async Task Main() { object o = new C(); switch (o) { case C c: System.Console.Write(1); break; default: return; } if (M() != null) { } } private static object M() { return new C(); } }"; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("C.<Main>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 162 (0xa2) .maxstack 2 .locals init (int V_0, object V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int C.<Main>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: object o = new C(); IL_0008: ldarg.0 IL_0009: newobj ""C..ctor()"" IL_000e: stfld ""object C.<Main>d__0.<o>5__1"" // sequence point: switch (o) IL_0013: ldarg.0 IL_0014: ldarg.0 IL_0015: ldfld ""object C.<Main>d__0.<o>5__1"" IL_001a: stloc.1 // sequence point: <hidden> IL_001b: ldloc.1 IL_001c: stfld ""object C.<Main>d__0.<>s__3"" // sequence point: <hidden> IL_0021: ldarg.0 IL_0022: ldarg.0 IL_0023: ldfld ""object C.<Main>d__0.<>s__3"" IL_0028: isinst ""C"" IL_002d: stfld ""C C.<Main>d__0.<c>5__2"" IL_0032: ldarg.0 IL_0033: ldfld ""C C.<Main>d__0.<c>5__2"" IL_0038: brtrue.s IL_003c IL_003a: br.s IL_0047 // sequence point: <hidden> IL_003c: br.s IL_003e // sequence point: System.Console.Write(1); IL_003e: ldc.i4.1 IL_003f: call ""void System.Console.Write(int)"" IL_0044: nop // sequence point: break; IL_0045: br.s IL_0049 // sequence point: return; IL_0047: leave.s IL_0086 // sequence point: <hidden> IL_0049: ldarg.0 IL_004a: ldnull IL_004b: stfld ""C C.<Main>d__0.<c>5__2"" IL_0050: ldarg.0 IL_0051: ldnull IL_0052: stfld ""object C.<Main>d__0.<>s__3"" // sequence point: if (M() != null) IL_0057: call ""object C.M()"" IL_005c: ldnull IL_005d: cgt.un IL_005f: stloc.2 // sequence point: <hidden> IL_0060: ldloc.2 IL_0061: brfalse.s IL_0065 // sequence point: { IL_0063: nop // sequence point: } IL_0064: nop // sequence point: <hidden> IL_0065: leave.s IL_0086 } catch System.Exception { // sequence point: <hidden> IL_0067: stloc.3 IL_0068: ldarg.0 IL_0069: ldc.i4.s -2 IL_006b: stfld ""int C.<Main>d__0.<>1__state"" IL_0070: ldarg.0 IL_0071: ldnull IL_0072: stfld ""object C.<Main>d__0.<o>5__1"" IL_0077: ldarg.0 IL_0078: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_007d: ldloc.3 IL_007e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0083: nop IL_0084: leave.s IL_00a1 } // sequence point: } IL_0086: ldarg.0 IL_0087: ldc.i4.s -2 IL_0089: stfld ""int C.<Main>d__0.<>1__state"" // sequence point: <hidden> IL_008e: ldarg.0 IL_008f: ldnull IL_0090: stfld ""object C.<Main>d__0.<o>5__1"" IL_0095: ldarg.0 IL_0096: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<Main>d__0.<>t__builder"" IL_009b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a0: nop IL_00a1: ret } ", sequencePoints: "C+<Main>d__0.MoveNext", source: source); } [Fact] public void SwitchExpressionWithPattern() { string source = WithWindowsLineBreaks(@" class C { static string M(object o) { return o switch { int i => $""Number: {i}"", _ => ""Don't know"" }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.M", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""55"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0x4"" startLine=""6"" startColumn=""18"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x2b"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0x37"" hidden=""true"" document=""1"" /> <entry offset=""0x3b"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3d""> <scope startOffset=""0x16"" endOffset=""0x2b""> <local name=""i"" il_index=""0"" il_start=""0x16"" il_end=""0x2b"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion #region DoStatement [Fact] public void DoStatement() { var source = WithWindowsLineBreaks( @"using System; public class SeqPointForWhile { public static void Main() { SeqPointForWhile obj = new SeqPointForWhile(); obj.While(234); } int field; public void While(int p) { do { p = (int)(p / 2); if (p > 100) { continue; } else if (p > 10) { field = 1; } else { break; } } while (p > 0); // SeqPt should be generated for [while (p > 0);] field = -1; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""SeqPointForWhile"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""28"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""55"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""24"" document=""1"" /> <entry offset=""0x13"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x14""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x14"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointForWhile"" name=""While"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointForWhile"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""1"" offset=""71"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""30"" document=""1"" /> <entry offset=""0x7"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0xd"" hidden=""true"" document=""1"" /> <entry offset=""0x10"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""14"" document=""1"" /> <entry offset=""0x11"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""26"" document=""1"" /> <entry offset=""0x13"" startLine=""22"" startColumn=""18"" endLine=""22"" endColumn=""29"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""14"" document=""1"" /> <entry offset=""0x1d"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""27"" document=""1"" /> <entry offset=""0x24"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""14"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""14"" document=""1"" /> <entry offset=""0x28"" startLine=""28"" startColumn=""17"" endLine=""28"" endColumn=""23"" document=""1"" /> <entry offset=""0x2a"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""30"" startColumn=""11"" endLine=""30"" endColumn=""25"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""20"" document=""1"" /> <entry offset=""0x3a"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Constructor [WorkItem(538317, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538317")] [Fact] public void ConstructorSequencePoints1() { var source = WithWindowsLineBreaks( @"namespace NS { public class MyClass { int intTest; public MyClass() { intTest = 123; } public MyClass(params int[] values) { intTest = values[0] + values[1] + values[2]; } public static int Main() { int intI = 1, intJ = 8; int intK = 3; // Can't step into Ctor MyClass mc = new MyClass(); // Can't step into Ctor mc = new MyClass(intI, intJ, intK); return mc.intTest - 12; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Dev10 vs. Roslyn // // Default Ctor (no param) // Dev10 Roslyn // ====================================================================================== // Code size 18 (0x12) // Code size 16 (0x10) // .maxstack 8 .maxstack 8 //* IL_0000: ldarg.0 *IL_0000: ldarg.0 // IL_0001: call IL_0001: callvirt // instance void [mscorlib]System.Object::.ctor() instance void [mscorlib]System.Object::.ctor() // IL_0006: nop *IL_0006: nop //* IL_0007: nop //* IL_0008: ldarg.0 *IL_0007: ldarg.0 // IL_0009: ldc.i4.s 123 IL_0008: ldc.i4.s 123 // IL_000b: stfld int32 NS.MyClass::intTest IL_000a: stfld int32 NS.MyClass::intTest // IL_0010: nop //* IL_0011: ret *IL_000f: ret // ----------------------------------------------------------------------------------------- // SeqPoint: 0, 7 ,8, 0x10 0, 6, 7, 0xf c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""NS.MyClass"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x10"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> <method containingType=""NS.MyClass"" name="".ctor"" parameterNames=""values""> <customDebugInfo> <forward declaringType=""NS.MyClass"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""57"" document=""1"" /> <entry offset=""0x19"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> <method containingType=""NS.MyClass"" name=""Main""> <customDebugInfo> <forward declaringType=""NS.MyClass"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""29"" /> <slot kind=""0"" offset=""56"" /> <slot kind=""0"" offset=""126"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""1"" /> <entry offset=""0x3"" startLine=""18"" startColumn=""27"" endLine=""18"" endColumn=""35"" document=""1"" /> <entry offset=""0x5"" startLine=""19"" startColumn=""13"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""40"" document=""1"" /> <entry offset=""0xd"" startLine=""25"" startColumn=""13"" endLine=""25"" endColumn=""48"" document=""1"" /> <entry offset=""0x25"" startLine=""27"" startColumn=""13"" endLine=""27"" endColumn=""36"" document=""1"" /> <entry offset=""0x32"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <local name=""intI"" il_index=""0"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""intJ"" il_index=""1"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""intK"" il_index=""2"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> <local name=""mc"" il_index=""3"" il_start=""0x0"" il_end=""0x35"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ConstructorSequencePoints2() { TestSequencePoints( @"using System; class D { public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class D { static D() [|{|] } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class D { [A] public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class D { [A] public D() : [|base()|] { } }", TestOptions.DebugDll); TestSequencePoints( @"using System; class A : Attribute {} class C { } class D { [A] [|public D()|] { } }", TestOptions.DebugDll); } #endregion #region Destructor [Fact] public void Destructors() { var source = @" using System; public class Base { ~Base() { Console.WriteLine(); } } public class Derived : Base { ~Derived() { Console.WriteLine(); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Base"" name=""Finalize""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0xa"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x12"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> </scope> </method> <method containingType=""Derived"" name=""Finalize""> <customDebugInfo> <forward declaringType=""Base"" methodName=""Finalize"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""29"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Field and Property Initializers [Fact] [WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")] public void TestPartialClassFieldInitializers() { var text1 = WithWindowsLineBreaks(@" public partial class C { int x = 1; } "); var text2 = WithWindowsLineBreaks(@" public partial class C { int y = 1; static void Main() { C c = new C(); } } "); // Having a unique name here may be important. The infrastructure of the pdb to xml conversion // loads the assembly into the ReflectionOnlyLoadFrom context. // So it's probably a good idea to have a new name for each assembly. var compilation = CreateCompilation(new SyntaxTree[] { Parse(text1, "a.cs"), Parse(text2, "b.cs") }); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" /> <file id=""2"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.Pdb); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""B4-EA-18-73-D2-0E-7F-15-51-4C-68-86-40-DF-E3-C3-97-9D-F6-B7"" /> <file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""BB-7A-A6-D2-B2-32-59-43-8C-98-7F-E1-98-8D-F0-94-68-E9-EB-80"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""15"" document=""2"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [Fact] [WorkItem(50611, "https://github.com/dotnet/roslyn/issues/50611")] public void TestPartialClassFieldInitializersWithLineDirectives() { var text1 = WithWindowsLineBreaks(@" using System; public partial class C { int x = 1; #line 12 ""foo.cs"" int z = Math.Abs(-3); int w = Math.Abs(4); #line 17 ""bar.cs"" double zed = Math.Sin(5); } #pragma checksum ""mah.cs"" ""{406EA660-64CF-4C82-B6F0-42D48172A799}"" ""ab007f1d23d9"" "); var text2 = WithWindowsLineBreaks(@" using System; public partial class C { int y = 1; int x2 = 1; #line 12 ""foo2.cs"" int z2 = Math.Abs(-3); int w2 = Math.Abs(4); } "); var text3 = WithWindowsLineBreaks(@" using System; public partial class C { #line 112 ""mah.cs"" int y3 = 1; int x3 = 1; int z3 = Math.Abs(-3); #line default int w3 = Math.Abs(4); double zed3 = Math.Sin(5); C() { Console.WriteLine(""hi""); } static void Main() { C c = new C(); } } "); //Having a unique name here may be important. The infrastructure of the pdb to xml conversion //loads the assembly into the ReflectionOnlyLoadFrom context. //So it's probably a good idea to have a new name for each assembly. var compilation = CreateCompilation(new[] { Parse(text1, "a.cs"), Parse(text2, "b.cs"), Parse(text3, "a.cs") }, options: TestOptions.DebugDll); compilation.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name=""a.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""E2-3B-47-02-DC-E4-8D-B4-FF-00-67-90-31-68-74-C0-06-D7-39-0E"" /> <file id=""2"" name=""b.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-CE-E5-E9-CB-53-E5-EF-C1-7F-2C-53-EC-02-FE-5C-34-2C-EF-94"" /> <file id=""3"" name=""foo.cs"" language=""C#"" /> <file id=""4"" name=""bar.cs"" language=""C#"" /> <file id=""5"" name=""foo2.cs"" language=""C#"" /> <file id=""6"" name=""mah.cs"" language=""C#"" checksumAlgorithm=""406ea660-64cf-4c82-b6f0-42d48172a799"" checksum=""AB-00-7F-1D-23-D9"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""26"" document=""3"" /> <entry offset=""0x14"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""25"" document=""3"" /> <entry offset=""0x20"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""30"" document=""4"" /> <entry offset=""0x34"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""15"" document=""2"" /> <entry offset=""0x3b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""16"" document=""2"" /> <entry offset=""0x42"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""27"" document=""5"" /> <entry offset=""0x4f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""26"" document=""5"" /> <entry offset=""0x5b"" startLine=""112"" startColumn=""5"" endLine=""112"" endColumn=""16"" document=""6"" /> <entry offset=""0x62"" startLine=""113"" startColumn=""5"" endLine=""113"" endColumn=""16"" document=""6"" /> <entry offset=""0x69"" startLine=""114"" startColumn=""5"" endLine=""114"" endColumn=""27"" document=""6"" /> <entry offset=""0x76"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""26"" document=""1"" /> <entry offset=""0x82"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x96"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" /> <entry offset=""0x9d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x9e"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""33"" document=""1"" /> <entry offset=""0xa9"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(543313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543313")] [Fact] public void TestFieldInitializerExpressionLambda() { var source = @" class C { int x = ((System.Func<int, int>)(z => z))(1); } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <lambda offset=""-6"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""50"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__1_0"" parameterNames=""z""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""43"" endLine=""4"" endColumn=""44"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FieldInitializerSequencePointSpans() { var source = @" class C { int x = 1, y = 2; } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""14"" document=""1"" /> <entry offset=""0x7"" startLine=""4"" startColumn=""16"" endLine=""4"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Auto-Property [WorkItem(820806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820806")] [Fact] public void BreakpointForAutoImplementedProperty() { var source = @" public class C { public static int AutoProp1 { get; private set; } internal string AutoProp2 { get; set; } internal protected C AutoProp3 { internal get; set; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_AutoProp1""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""35"" endLine=""4"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp1"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""40"" endLine=""4"" endColumn=""52"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""get_AutoProp2""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""33"" endLine=""5"" endColumn=""37"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp2"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""38"" endLine=""5"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""get_AutoProp3""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""38"" endLine=""6"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_AutoProp3"" parameterNames=""value""> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""52"" endLine=""6"" endColumn=""56"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void PropertyDeclaration() { TestSequencePoints( @"using System; public class C { int P { [|get;|] set; } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get; [|set;|] } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get [|{|] return 0; } } }", TestOptions.DebugDll); TestSequencePoints( @"using System; public class C { int P { get; } = [|int.Parse(""42"")|]; }", TestOptions.DebugDll, TestOptions.Regular); } #endregion #region ReturnStatement [Fact] public void Return_Implicit() { var source = @"class C { static void Main() { } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void Return_Explicit() { var source = @"class C { static void Main() { return; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" document=""1"" /> <entry offset=""0x3"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(538298, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538298")] [Fact] public void RegressSeqPtEndOfMethodAfterReturn() { var source = WithWindowsLineBreaks( @"using System; public class SeqPointAfterReturn { public static int Main() { int ret = 0; ReturnVoid(100); if (field != ""Even"") ret = 1; ReturnVoid(99); if (field != ""Odd"") ret = ret + 1; string rets = ReturnValue(101); if (rets != ""Odd"") ret = ret + 1; rets = ReturnValue(102); if (rets != ""Even"") ret = ret + 1; return ret; } static string field; public static void ReturnVoid(int p) { int x = (int)(p % 2); if (x == 0) { field = ""Even""; } else { field = ""Odd""; } } public static string ReturnValue(int p) { int x = (int)(p % 2); if (x == 0) { return ""Even""; } else { return ""Odd""; } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); // Expected are current actual output plus Two extra expected SeqPt: // <entry offset=""0x73"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> // <entry offset=""0x22"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" /> // // Note: NOT include other differences between Roslyn and Dev10, as they are filed in separated bugs c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""SeqPointAfterReturn"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""204"" /> <slot kind=""1"" offset=""59"" /> <slot kind=""1"" offset=""138"" /> <slot kind=""1"" offset=""238"" /> <slot kind=""1"" offset=""330"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""29"" document=""1"" /> <entry offset=""0x1b"" hidden=""true"" document=""1"" /> <entry offset=""0x1e"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""21"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x28"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""28"" document=""1"" /> <entry offset=""0x38"" hidden=""true"" document=""1"" /> <entry offset=""0x3b"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""27"" document=""1"" /> <entry offset=""0x3f"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""40"" document=""1"" /> <entry offset=""0x47"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""27"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""27"" document=""1"" /> <entry offset=""0x5c"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""33"" document=""1"" /> <entry offset=""0x64"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""28"" document=""1"" /> <entry offset=""0x71"" hidden=""true"" document=""1"" /> <entry offset=""0x75"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""27"" document=""1"" /> <entry offset=""0x79"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""20"" document=""1"" /> <entry offset=""0x7e"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x81""> <namespace name=""System"" /> <local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" /> <local name=""rets"" il_index=""1"" il_start=""0x0"" il_end=""0x81"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointAfterReturn"" name=""ReturnVoid"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""1"" offset=""42"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""30"" document=""1"" /> <entry offset=""0x5"" startLine=""31"" startColumn=""9"" endLine=""31"" endColumn=""20"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""33"" startColumn=""13"" endLine=""33"" endColumn=""28"" document=""1"" /> <entry offset=""0x18"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""37"" startColumn=""13"" endLine=""37"" endColumn=""27"" document=""1"" /> <entry offset=""0x26"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""39"" startColumn=""5"" endLine=""39"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> </scope> </method> <method containingType=""SeqPointAfterReturn"" name=""ReturnValue"" parameterNames=""p""> <customDebugInfo> <forward declaringType=""SeqPointAfterReturn"" methodName=""Main"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""1"" offset=""42"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""42"" startColumn=""5"" endLine=""42"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""43"" startColumn=""9"" endLine=""43"" endColumn=""30"" document=""1"" /> <entry offset=""0x5"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""20"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""45"" startColumn=""9"" endLine=""45"" endColumn=""10"" document=""1"" /> <entry offset=""0xe"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""27"" document=""1"" /> <entry offset=""0x16"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""50"" startColumn=""13"" endLine=""50"" endColumn=""26"" document=""1"" /> <entry offset=""0x1f"" startLine=""52"" startColumn=""5"" endLine=""52"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region Exception Handling [WorkItem(542064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542064")] [Fact] public void ExceptionHandling() { var source = WithWindowsLineBreaks(@" class Test { static int Main() { int ret = 0; // stop 1 try { // stop 2 throw new System.Exception(); // stop 3 } catch (System.Exception e) // stop 4 { // stop 5 ret = 1; // stop 6 } try { // stop 7 throw new System.Exception(); // stop 8 } catch // stop 9 { // stop 10 return ret; // stop 11 } } } "); // Dev12 inserts an additional sequence point on catch clause, just before // the exception object is assigned to the variable. We don't place that sequence point. // Also the scope of he exception variable is different. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("Test.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""147"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""42"" document=""1"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""35"" document=""1"" /> <entry offset=""0xb"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0xe"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""42"" document=""1"" /> <entry offset=""0x19"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x1a"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x1b"" startLine=""22"" startColumn=""13"" endLine=""22"" endColumn=""24"" document=""1"" /> <entry offset=""0x1f"" startLine=""25"" startColumn=""5"" endLine=""25"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <local name=""ret"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <scope startOffset=""0xa"" endOffset=""0x11""> <local name=""e"" il_index=""1"" il_start=""0xa"" il_end=""0x11"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug1() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class Test { static string filter(Exception e) { return null; } static void Main() { try { throw new InvalidOperationException(); } catch (IOException e) when (filter(e) != null) { Console.WriteLine(); } catch (Exception e) when (filter(e) != null) { Console.WriteLine(); } } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 89 (0x59) .maxstack 2 .locals init (System.IO.IOException V_0, //e bool V_1, System.Exception V_2, //e bool V_3) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.InvalidOperationException..ctor()"" IL_0007: throw } filter { ~IL_0008: isinst ""System.IO.IOException"" IL_000d: dup IL_000e: brtrue.s IL_0014 IL_0010: pop IL_0011: ldc.i4.0 IL_0012: br.s IL_0023 IL_0014: stloc.0 -IL_0015: ldloc.0 IL_0016: call ""string Test.filter(System.Exception)"" IL_001b: ldnull IL_001c: cgt.un IL_001e: stloc.1 ~IL_001f: ldloc.1 IL_0020: ldc.i4.0 IL_0021: cgt.un IL_0023: endfilter } // end filter { // handler ~IL_0025: pop -IL_0026: nop -IL_0027: call ""void System.Console.WriteLine()"" IL_002c: nop -IL_002d: nop IL_002e: leave.s IL_0058 } filter { ~IL_0030: isinst ""System.Exception"" IL_0035: dup IL_0036: brtrue.s IL_003c IL_0038: pop IL_0039: ldc.i4.0 IL_003a: br.s IL_004b IL_003c: stloc.2 -IL_003d: ldloc.2 IL_003e: call ""string Test.filter(System.Exception)"" IL_0043: ldnull IL_0044: cgt.un IL_0046: stloc.3 ~IL_0047: ldloc.3 IL_0048: ldc.i4.0 IL_0049: cgt.un IL_004b: endfilter } // end filter { // handler ~IL_004d: pop -IL_004e: nop -IL_004f: call ""void System.Console.WriteLine()"" IL_0054: nop -IL_0055: nop IL_0056: leave.s IL_0058 } -IL_0058: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName=""filter"" parameterNames=""e"" /> <encLocalSlotMap> <slot kind=""0"" offset=""104"" /> <slot kind=""1"" offset=""120"" /> <slot kind=""0"" offset=""216"" /> <slot kind=""1"" offset=""230"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""51"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" startLine=""18"" startColumn=""31"" endLine=""18"" endColumn=""55"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x27"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""33"" document=""1"" /> <entry offset=""0x2d"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x3d"" startLine=""22"" startColumn=""29"" endLine=""22"" endColumn=""53"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""10"" document=""1"" /> <entry offset=""0x4f"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""33"" document=""1"" /> <entry offset=""0x55"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> <entry offset=""0x58"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x59""> <scope startOffset=""0x8"" endOffset=""0x30""> <local name=""e"" il_index=""0"" il_start=""0x8"" il_end=""0x30"" attributes=""0"" /> </scope> <scope startOffset=""0x30"" endOffset=""0x58""> <local name=""e"" il_index=""2"" il_start=""0x30"" il_end=""0x58"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug2() { var source = WithWindowsLineBreaks(@" class Test { static void Main() { try { throw new System.Exception(); } catch when (F()) { System.Console.WriteLine(); } } private static bool F() { return true; } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 2 .locals init (bool V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.Exception..ctor()"" IL_0007: throw } filter { ~IL_0008: pop -IL_0009: call ""bool Test.F()"" IL_000e: stloc.0 ~IL_000f: ldloc.0 IL_0010: ldc.i4.0 IL_0011: cgt.un IL_0013: endfilter } // end filter { // handler ~IL_0015: pop -IL_0016: nop -IL_0017: call ""void System.Console.WriteLine()"" IL_001c: nop -IL_001d: nop IL_001e: leave.s IL_0020 } -IL_0020: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""95"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" startLine=""10"" startColumn=""15"" endLine=""10"" endColumn=""25"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""40"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Debug3() { var source = WithWindowsLineBreaks(@" class Test { static bool a = true; static void Main() { try { throw new System.Exception(); } catch when (a) { System.Console.WriteLine(); } } } "); var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll)); v.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 2 .locals init (bool V_0) -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""System.Exception..ctor()"" IL_0007: throw } filter { ~IL_0008: pop -IL_0009: ldsfld ""bool Test.a"" IL_000e: stloc.0 ~IL_000f: ldloc.0 IL_0010: ldc.i4.0 IL_0011: cgt.un IL_0013: endfilter } // end filter { // handler ~IL_0015: pop -IL_0016: nop -IL_0017: call ""void System.Console.WriteLine()"" IL_001c: nop -IL_001d: nop IL_001e: leave.s IL_0020 } -IL_0020: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""1"" offset=""95"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0x9"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" /> <entry offset=""0x1d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x20"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(2911, "https://github.com/dotnet/roslyn/issues/2911")] [Fact] public void ExceptionHandling_Filter_Release3() { var source = @" class Test { static bool a = true; static void Main() { try { throw new System.Exception(); } catch when (a) { System.Console.WriteLine(); } } } "; var v = CompileAndVerify(CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll)); v.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .try { -IL_0000: newobj ""System.Exception..ctor()"" IL_0005: throw } filter { ~IL_0006: pop -IL_0007: ldsfld ""bool Test.a"" IL_000c: ldc.i4.0 IL_000d: cgt.un IL_000f: endfilter } // end filter { // handler ~IL_0011: pop -IL_0012: call ""void System.Console.WriteLine()"" -IL_0017: leave.s IL_0019 } -IL_0019: ret } ", sequencePoints: "Test.Main"); v.VerifyPdb("Test.Main", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""42"" document=""1"" /> <entry offset=""0x6"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""15"" endLine=""12"" endColumn=""23"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""40"" document=""1"" /> <entry offset=""0x17"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x19"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(778655, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778655")] [Fact] public void BranchToStartOfTry() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { string str = null; bool isEmpty = string.IsNullOrEmpty(str); // isEmpty is always true here, so it should never go thru this if statement. if (!isEmpty) { throw new Exception(); } try { Console.WriteLine(); } catch { } } } "); // Note the hidden sequence point @IL_0019. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""1"" offset=""177"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""27"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""50"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""22"" document=""1"" /> <entry offset=""0xf"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x13"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""35"" document=""1"" /> <entry offset=""0x19"" hidden=""true"" document=""1"" /> <entry offset=""0x1a"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1b"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""33"" document=""1"" /> <entry offset=""0x21"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x24"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""14"" document=""1"" /> <entry offset=""0x25"" startLine=""21"" startColumn=""9"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x29"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""str"" il_index=""0"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" /> <local name=""isEmpty"" il_index=""1"" il_start=""0x0"" il_end=""0x2a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region UsingStatement [Fact] public void UsingStatement_EmbeddedStatement() { var source = WithWindowsLineBreaks(@" public class DisposableClass : System.IDisposable { public DisposableClass(int a) { } public void Dispose() { } } class C { static void Main() { using (DisposableClass a = new DisposableClass(1), b = new DisposableClass(2)) System.Console.WriteLine(""First""); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 53 (0x35) .maxstack 1 .locals init (DisposableClass V_0, //a DisposableClass V_1) //b // sequence point: { IL_0000: nop // sequence point: DisposableClass a = new DisposableClass(1) IL_0001: ldc.i4.1 IL_0002: newobj ""DisposableClass..ctor(int)"" IL_0007: stloc.0 .try { // sequence point: b = new DisposableClass(2) IL_0008: ldc.i4.2 IL_0009: newobj ""DisposableClass..ctor(int)"" IL_000e: stloc.1 .try { // sequence point: System.Console.WriteLine(""First""); IL_000f: ldstr ""First"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: nop IL_001a: leave.s IL_0027 } finally { // sequence point: <hidden> IL_001c: ldloc.1 IL_001d: brfalse.s IL_0026 IL_001f: ldloc.1 IL_0020: callvirt ""void System.IDisposable.Dispose()"" IL_0025: nop // sequence point: <hidden> IL_0026: endfinally } // sequence point: <hidden> IL_0027: leave.s IL_0034 } finally { // sequence point: <hidden> IL_0029: ldloc.0 IL_002a: brfalse.s IL_0033 IL_002c: ldloc.0 IL_002d: callvirt ""void System.IDisposable.Dispose()"" IL_0032: nop // sequence point: <hidden> IL_0033: endfinally } // sequence point: } IL_0034: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" /> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" /> <entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" /> <entry offset=""0xf"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""47"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> <entry offset=""0x34"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x35""> <scope startOffset=""0x1"" endOffset=""0x34""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x34"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void UsingStatement_Block() { var source = WithWindowsLineBreaks(@" public class DisposableClass : System.IDisposable { public DisposableClass(int a) { } public void Dispose() { } } class C { static void Main() { using (DisposableClass c = new DisposableClass(3), d = new DisposableClass(4)) { System.Console.WriteLine(""Second""); } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 55 (0x37) .maxstack 1 .locals init (DisposableClass V_0, //c DisposableClass V_1) //d // sequence point: { IL_0000: nop // sequence point: DisposableClass c = new DisposableClass(3) IL_0001: ldc.i4.3 IL_0002: newobj ""DisposableClass..ctor(int)"" IL_0007: stloc.0 .try { // sequence point: d = new DisposableClass(4) IL_0008: ldc.i4.4 IL_0009: newobj ""DisposableClass..ctor(int)"" IL_000e: stloc.1 .try { // sequence point: { IL_000f: nop // sequence point: System.Console.WriteLine(""Second""); IL_0010: ldstr ""Second"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: nop // sequence point: } IL_001b: nop IL_001c: leave.s IL_0029 } finally { // sequence point: <hidden> IL_001e: ldloc.1 IL_001f: brfalse.s IL_0028 IL_0021: ldloc.1 IL_0022: callvirt ""void System.IDisposable.Dispose()"" IL_0027: nop // sequence point: <hidden> IL_0028: endfinally } // sequence point: <hidden> IL_0029: leave.s IL_0036 } finally { // sequence point: <hidden> IL_002b: ldloc.0 IL_002c: brfalse.s IL_0035 IL_002e: ldloc.0 IL_002f: callvirt ""void System.IDisposable.Dispose()"" IL_0034: nop // sequence point: <hidden> IL_0035: endfinally } // sequence point: } IL_0036: ret } " ); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""DisposableClass"" methodName="".ctor"" parameterNames=""a"" /> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""62"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""58"" document=""1"" /> <entry offset=""0x8"" startLine=""12"" startColumn=""60"" endLine=""12"" endColumn=""86"" document=""1"" /> <entry offset=""0xf"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x10"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""48"" document=""1"" /> <entry offset=""0x1b"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" hidden=""true"" document=""1"" /> <entry offset=""0x28"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x36"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x37""> <scope startOffset=""0x1"" endOffset=""0x36""> <local name=""c"" il_index=""0"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" /> <local name=""d"" il_index=""1"" il_start=""0x1"" il_end=""0x36"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedConditional() { var source = @" class C { bool F() { bool x = true; bool value = false; using (var stream = new System.IO.MemoryStream()) if (x) { value = true; } else value = false; return value; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 45 (0x2d) .maxstack 1 .locals init (bool V_0, //x bool V_1, //value System.IO.MemoryStream V_2, //stream bool V_3, bool V_4) // sequence point: { IL_0000: nop // sequence point: bool x = true; IL_0001: ldc.i4.1 IL_0002: stloc.0 // sequence point: bool value = false; IL_0003: ldc.i4.0 IL_0004: stloc.1 // sequence point: var stream = new System.IO.MemoryStream() IL_0005: newobj ""System.IO.MemoryStream..ctor()"" IL_000a: stloc.2 .try { // sequence point: if (x) IL_000b: ldloc.0 IL_000c: stloc.3 // sequence point: <hidden> IL_000d: ldloc.3 IL_000e: brfalse.s IL_0016 // sequence point: { IL_0010: nop // sequence point: value = true; IL_0011: ldc.i4.1 IL_0012: stloc.1 // sequence point: } IL_0013: nop // sequence point: <hidden> IL_0014: br.s IL_0018 // sequence point: value = false; IL_0016: ldc.i4.0 IL_0017: stloc.1 // sequence point: <hidden> IL_0018: leave.s IL_0025 } finally { // sequence point: <hidden> IL_001a: ldloc.2 IL_001b: brfalse.s IL_0024 IL_001d: ldloc.2 IL_001e: callvirt ""void System.IDisposable.Dispose()"" IL_0023: nop // sequence point: <hidden> IL_0024: endfinally } // sequence point: return value; IL_0025: ldloc.1 IL_0026: stloc.s V_4 IL_0028: br.s IL_002a // sequence point: } IL_002a: ldloc.s V_4 IL_002c: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedConditional2() { var source = @" class C { bool F() { bool x = true; bool value = false; using (var stream = new System.IO.MemoryStream()) if (x) { value = true; } else { value = false; } return value; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 47 (0x2f) .maxstack 1 .locals init (bool V_0, //x bool V_1, //value System.IO.MemoryStream V_2, //stream bool V_3, bool V_4) // sequence point: { IL_0000: nop // sequence point: bool x = true; IL_0001: ldc.i4.1 IL_0002: stloc.0 // sequence point: bool value = false; IL_0003: ldc.i4.0 IL_0004: stloc.1 // sequence point: var stream = new System.IO.MemoryStream() IL_0005: newobj ""System.IO.MemoryStream..ctor()"" IL_000a: stloc.2 .try { // sequence point: if (x) IL_000b: ldloc.0 IL_000c: stloc.3 // sequence point: <hidden> IL_000d: ldloc.3 IL_000e: brfalse.s IL_0016 // sequence point: { IL_0010: nop // sequence point: value = true; IL_0011: ldc.i4.1 IL_0012: stloc.1 // sequence point: } IL_0013: nop // sequence point: <hidden> IL_0014: br.s IL_001a // sequence point: { IL_0016: nop // sequence point: value = false; IL_0017: ldc.i4.0 IL_0018: stloc.1 // sequence point: } IL_0019: nop // sequence point: <hidden> IL_001a: leave.s IL_0027 } finally { // sequence point: <hidden> IL_001c: ldloc.2 IL_001d: brfalse.s IL_0026 IL_001f: ldloc.2 IL_0020: callvirt ""void System.IDisposable.Dispose()"" IL_0025: nop // sequence point: <hidden> IL_0026: endfinally } // sequence point: return value; IL_0027: ldloc.1 IL_0028: stloc.s V_4 IL_002a: br.s IL_002c // sequence point: } IL_002c: ldloc.s V_4 IL_002e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedWhile() { var source = @" class C { void F(bool x) { using (var stream = new System.IO.MemoryStream()) while (x) x = false; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //stream bool V_1) // sequence point: { IL_0000: nop // sequence point: var stream = new System.IO.MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: br.s IL_000c // sequence point: x = false; IL_0009: ldc.i4.0 IL_000a: starg.s V_1 // sequence point: while (x) IL_000c: ldarg.1 IL_000d: stloc.1 // sequence point: <hidden> IL_000e: ldloc.1 IL_000f: brtrue.s IL_0009 IL_0011: leave.s IL_001e } finally { // sequence point: <hidden> IL_0013: ldloc.0 IL_0014: brfalse.s IL_001d IL_0016: ldloc.0 IL_0017: callvirt ""void System.IDisposable.Dispose()"" IL_001c: nop // sequence point: <hidden> IL_001d: endfinally } // sequence point: } IL_001e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void UsingStatement_EmbeddedFor() { var source = @" class C { void F(bool x) { using (var stream = new System.IO.MemoryStream()) for ( ; x == true; ) x = false; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //stream bool V_1) // sequence point: { IL_0000: nop // sequence point: var stream = new System.IO.MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: <hidden> IL_0007: br.s IL_000c // sequence point: x = false; IL_0009: ldc.i4.0 IL_000a: starg.s V_1 // sequence point: x == true IL_000c: ldarg.1 IL_000d: stloc.1 // sequence point: <hidden> IL_000e: ldloc.1 IL_000f: brtrue.s IL_0009 IL_0011: leave.s IL_001e } finally { // sequence point: <hidden> IL_0013: ldloc.0 IL_0014: brfalse.s IL_001d IL_0016: ldloc.0 IL_0017: callvirt ""void System.IDisposable.Dispose()"" IL_001c: nop // sequence point: <hidden> IL_001d: endfinally } // sequence point: } IL_001e: ret } ", sequencePoints: "C.F", source: source); } [WorkItem(18844, "https://github.com/dotnet/roslyn/issues/18844")] [Fact] public void LockStatement_EmbeddedIf() { var source = @" class C { void F(bool x) { string y = """"; lock (y) if (!x) System.Console.Write(1); else System.Console.Write(2); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 58 (0x3a) .maxstack 2 .locals init (string V_0, //y string V_1, bool V_2, bool V_3) // sequence point: { IL_0000: nop // sequence point: string y = """"; IL_0001: ldstr """" IL_0006: stloc.0 // sequence point: lock (y) IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: ldc.i4.0 IL_000a: stloc.2 .try { IL_000b: ldloc.1 IL_000c: ldloca.s V_2 IL_000e: call ""void System.Threading.Monitor.Enter(object, ref bool)"" IL_0013: nop // sequence point: if (!x) IL_0014: ldarg.1 IL_0015: ldc.i4.0 IL_0016: ceq IL_0018: stloc.3 // sequence point: <hidden> IL_0019: ldloc.3 IL_001a: brfalse.s IL_0025 // sequence point: System.Console.Write(1); IL_001c: ldc.i4.1 IL_001d: call ""void System.Console.Write(int)"" IL_0022: nop // sequence point: <hidden> IL_0023: br.s IL_002c // sequence point: System.Console.Write(2); IL_0025: ldc.i4.2 IL_0026: call ""void System.Console.Write(int)"" IL_002b: nop // sequence point: <hidden> IL_002c: leave.s IL_0039 } finally { // sequence point: <hidden> IL_002e: ldloc.2 IL_002f: brfalse.s IL_0038 IL_0031: ldloc.1 IL_0032: call ""void System.Threading.Monitor.Exit(object)"" IL_0037: nop // sequence point: <hidden> IL_0038: endfinally } // sequence point: } IL_0039: ret } ", sequencePoints: "C.F", source: source); } #endregion #region Using Declaration [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_BodyBlockScope() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { static void Main() { using MemoryStream m = new MemoryStream(), n = new MemoryStream(); Console.WriteLine(1); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // Duplicate sequence point at `}` v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 45 (0x2d) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //m System.IO.MemoryStream V_1) //n // sequence point: { IL_0000: nop // sequence point: using MemoryStream m = new MemoryStream() IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: n = new MemoryStream() IL_0007: newobj ""System.IO.MemoryStream..ctor()"" IL_000c: stloc.1 .try { // sequence point: Console.WriteLine(1); IL_000d: ldc.i4.1 IL_000e: call ""void System.Console.WriteLine(int)"" IL_0013: nop // sequence point: } IL_0014: leave.s IL_002c } finally { // sequence point: <hidden> IL_0016: ldloc.1 IL_0017: brfalse.s IL_0020 IL_0019: ldloc.1 IL_001a: callvirt ""void System.IDisposable.Dispose()"" IL_001f: nop // sequence point: <hidden> IL_0020: endfinally } } finally { // sequence point: <hidden> IL_0021: ldloc.0 IL_0022: brfalse.s IL_002b IL_0024: ldloc.0 IL_0025: callvirt ""void System.IDisposable.Dispose()"" IL_002a: nop // sequence point: <hidden> IL_002b: endfinally } // sequence point: } IL_002c: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""30"" /> <slot kind=""0"" offset=""54"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""50"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""52"" endLine=""8"" endColumn=""74"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x14"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x20"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2b"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2d""> <namespace name=""System"" /> <namespace name=""System.IO"" /> <local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> <local name=""n"" il_index=""1"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_BodyBlockScopeWithReturn() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { static int Main() { using MemoryStream m = new MemoryStream(); Console.WriteLine(1); return 1; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // Duplicate sequence point at `}` v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 31 (0x1f) .maxstack 1 .locals init (System.IO.MemoryStream V_0, //m int V_1) // sequence point: { IL_0000: nop // sequence point: using MemoryStream m = new MemoryStream(); IL_0001: newobj ""System.IO.MemoryStream..ctor()"" IL_0006: stloc.0 .try { // sequence point: Console.WriteLine(1); IL_0007: ldc.i4.1 IL_0008: call ""void System.Console.WriteLine(int)"" IL_000d: nop // sequence point: return 1; IL_000e: ldc.i4.1 IL_000f: stloc.1 IL_0010: leave.s IL_001d } finally { // sequence point: <hidden> IL_0012: ldloc.0 IL_0013: brfalse.s IL_001c IL_0015: ldloc.0 IL_0016: callvirt ""void System.IDisposable.Dispose()"" IL_001b: nop // sequence point: <hidden> IL_001c: endfinally } // sequence point: } IL_001d: ldloc.1 IL_001e: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""30"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""51"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0xe"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""18"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x1c"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <namespace name=""System"" /> <namespace name=""System.IO"" /> <local name=""m"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37417, "https://github.com/dotnet/roslyn/issues/37417")] [Fact] public void UsingDeclaration_IfBodyScope() { var source = WithWindowsLineBreaks(@" using System; using System.IO; class C { public static bool G() => true; static void Main() { if (G()) { using var m = new MemoryStream(); Console.WriteLine(1); } Console.WriteLine(2); } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); // TODO: https://github.com/dotnet/roslyn/issues/37417 // In this case the sequence point `}` is not emitted on the leave instruction, // but to a nop instruction following the disposal. v.VerifyIL("C.Main", sequencePoints: "C.Main", source: source, expectedIL: @" { // Code size 46 (0x2e) .maxstack 1 .locals init (bool V_0, System.IO.MemoryStream V_1) //m // sequence point: { IL_0000: nop // sequence point: if (G()) IL_0001: call ""bool C.G()"" IL_0006: stloc.0 // sequence point: <hidden> IL_0007: ldloc.0 IL_0008: brfalse.s IL_0026 // sequence point: { IL_000a: nop // sequence point: using var m = new MemoryStream(); IL_000b: newobj ""System.IO.MemoryStream..ctor()"" IL_0010: stloc.1 .try { // sequence point: Console.WriteLine(1); IL_0011: ldc.i4.1 IL_0012: call ""void System.Console.WriteLine(int)"" IL_0017: nop IL_0018: leave.s IL_0025 } finally { // sequence point: <hidden> IL_001a: ldloc.1 IL_001b: brfalse.s IL_0024 IL_001d: ldloc.1 IL_001e: callvirt ""void System.IDisposable.Dispose()"" IL_0023: nop // sequence point: <hidden> IL_0024: endfinally } // sequence point: } IL_0025: nop // sequence point: Console.WriteLine(2); IL_0026: ldc.i4.2 IL_0027: call ""void System.Console.WriteLine(int)"" IL_002c: nop // sequence point: } IL_002d: ret } "); c.VerifyPdb("C.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" /> <encLocalSlotMap> <slot kind=""1"" offset=""11"" /> <slot kind=""0"" offset=""55"" /> </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=""17"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""46"" document=""1"" /> <entry offset=""0x11"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""34"" document=""1"" /> <entry offset=""0x1a"" hidden=""true"" document=""1"" /> <entry offset=""0x24"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""30"" document=""1"" /> <entry offset=""0x2d"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2e""> <scope startOffset=""0xa"" endOffset=""0x26""> <local name=""m"" il_index=""1"" il_start=""0xa"" il_end=""0x26"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } #endregion // LockStatement tested in CodeGenLock #region Anonymous Type [Fact] public void AnonymousType_Empty() { var source = WithWindowsLineBreaks(@" class Program { static void Main(string[] args) { var o = new {}; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x8"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void AnonymousType_NonEmpty() { var source = WithWindowsLineBreaks(@" class Program { static void Main(string[] args) { var o = new { a = 1 }; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""31"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""o"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region FixedStatement [Fact] public void FixedStatementSingleAddress() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int x; static void Main() { C c = new C(); fixed (int* p = &c.x) { *p = 1; } Console.WriteLine(c.x); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""47"" /> <slot kind=""9"" offset=""47"" /> </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=""23"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""16"" endLine=""11"" endColumn=""29"" document=""1"" /> <entry offset=""0x11"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""20"" document=""1"" /> <entry offset=""0x15"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x19"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""32"" document=""1"" /> <entry offset=""0x25"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x26""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x19""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x19"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementSingleString() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { static void Main() { fixed (char* p = ""hello"") { Console.WriteLine(*p); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""24"" /> <slot kind=""9"" offset=""24"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x15"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x1e"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x21""> <local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x21"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementSingleArray() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int[] a = new int[1]; static void Main() { C c = new C(); Console.Write(c.a[0]); fixed (int* p = c.a) { (*p)++; } Console.Write(c.a[0]); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""79"" /> <slot kind=""temp"" /> </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=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x15"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""28"" document=""1"" /> <entry offset=""0x32"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x33"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" /> <entry offset=""0x39"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""31"" document=""1"" /> <entry offset=""0x4a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4b""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x4b"" attributes=""0"" /> <scope startOffset=""0x15"" endOffset=""0x3c""> <local name=""p"" il_index=""1"" il_start=""0x15"" il_end=""0x3c"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleAddresses() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int x; int y; static void Main() { C c = new C(); fixed (int* p = &c.x, q = &c.y) { *p = 1; *q = 2; } Console.WriteLine(c.x + c.y); } } "); // NOTE: stop on each declarator. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""47"" /> <slot kind=""0"" offset=""57"" /> <slot kind=""9"" offset=""47"" /> <slot kind=""9"" offset=""57"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0xe"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""29"" document=""1"" /> <entry offset=""0x19"" startLine=""12"" startColumn=""31"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""20"" document=""1"" /> <entry offset=""0x21"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""20"" document=""1"" /> <entry offset=""0x24"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""38"" document=""1"" /> <entry offset=""0x3f"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x40"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x2c""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x2c"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleStrings() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { static void Main() { fixed (char* p = ""hello"", q = ""goodbye"") { Console.Write(*p); Console.Write(*q); } } } "); // NOTE: stop on each declarator. var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""24"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""9"" offset=""24"" /> <slot kind=""9"" offset=""37"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""33"" document=""1"" /> <entry offset=""0x1b"" startLine=""8"" startColumn=""35"" endLine=""8"" endColumn=""48"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x2a"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""31"" document=""1"" /> <entry offset=""0x32"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""31"" document=""1"" /> <entry offset=""0x3a"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3f"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x3f""> <local name=""p"" il_index=""0"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" /> <local name=""q"" il_index=""1"" il_start=""0x1"" il_end=""0x3f"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleArrays() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { int[] a = new int[1]; int[] b = new int[1]; static void Main() { C c = new C(); Console.Write(c.a[0]); Console.Write(c.b[0]); fixed (int* p = c.a, q = c.b) { *p = 1; *q = 2; } Console.Write(c.a[0]); Console.Write(c.b[0]); } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""111"" /> <slot kind=""0"" offset=""120"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""1"" /> <entry offset=""0x15"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""31"" document=""1"" /> <entry offset=""0x23"" startLine=""14"" startColumn=""16"" endLine=""14"" endColumn=""28"" document=""1"" /> <entry offset=""0x40"" startLine=""14"" startColumn=""30"" endLine=""14"" endColumn=""37"" document=""1"" /> <entry offset=""0x60"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""1"" /> <entry offset=""0x61"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""20"" document=""1"" /> <entry offset=""0x64"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""20"" document=""1"" /> <entry offset=""0x67"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" document=""1"" /> <entry offset=""0x68"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""31"" document=""1"" /> <entry offset=""0x7b"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""31"" document=""1"" /> <entry offset=""0x89"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8a""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x8a"" attributes=""0"" /> <scope startOffset=""0x23"" endOffset=""0x6d""> <local name=""p"" il_index=""1"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x23"" il_end=""0x6d"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""1"" /> <entry offset=""0xc"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void FixedStatementMultipleMixed() { var source = WithWindowsLineBreaks(@" using System; unsafe class C { char c = 'a'; char[] a = new char[1]; static void Main() { C c = new C(); fixed (char* p = &c.c, q = c.a, r = ""hello"") { Console.Write((int)*p); Console.Write((int)*q); Console.Write((int)*r); } } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""48"" /> <slot kind=""0"" offset=""58"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""9"" offset=""48"" /> <slot kind=""temp"" /> <slot kind=""9"" offset=""67"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0xf"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""32"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x3a"" startLine=""12"" startColumn=""41"" endLine=""12"" endColumn=""52"" document=""1"" /> <entry offset=""0x49"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x4a"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""36"" document=""1"" /> <entry offset=""0x52"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""36"" document=""1"" /> <entry offset=""0x5a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""36"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6e""> <namespace name=""System"" /> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x6e"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x6d""> <local name=""p"" il_index=""1"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> <local name=""q"" il_index=""2"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> <local name=""r"" il_index=""3"" il_start=""0x7"" il_end=""0x6d"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""28"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Line Directives [Fact] public void LineDirective() { var source = @" #line 50 ""foo.cs"" using System; unsafe class C { static void Main() { Console.Write(1); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""foo.cs"" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""56"" startColumn=""5"" endLine=""56"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""57"" startColumn=""9"" endLine=""57"" endColumn=""26"" document=""1"" /> <entry offset=""0x8"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(544917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544917")] [Fact] public void DisabledLineDirective() { var source = @" #if false #line 50 ""foo.cs"" #endif using System; unsafe class C { static void Main() { Console.Write(1); } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugExe); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""26"" document=""1"" /> <entry offset=""0x8"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestLineDirectivesHidden() { var text1 = WithWindowsLineBreaks(@" using System; public class C { public void Foo() { foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } #line hidden foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } #line default foreach (var x in new int[] { 1, 2, 3, 4 }) { Console.WriteLine(x); } } } "); var compilation = CreateCompilation(text1, options: TestOptions.DebugDll); compilation.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Foo""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""6"" offset=""11"" /> <slot kind=""8"" offset=""11"" /> <slot kind=""0"" offset=""11"" /> <slot kind=""6"" offset=""137"" /> <slot kind=""8"" offset=""137"" /> <slot kind=""0"" offset=""137"" /> <slot kind=""6"" offset=""264"" /> <slot kind=""8"" offset=""264"" /> <slot kind=""0"" offset=""264"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""16"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""51"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""18"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x1c"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""34"" document=""1"" /> <entry offset=""0x24"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x25"" hidden=""true"" document=""1"" /> <entry offset=""0x29"" startLine=""7"" startColumn=""24"" endLine=""7"" endColumn=""26"" document=""1"" /> <entry offset=""0x2f"" hidden=""true"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" hidden=""true"" document=""1"" /> <entry offset=""0x4d"" hidden=""true"" document=""1"" /> <entry offset=""0x4e"" hidden=""true"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" hidden=""true"" document=""1"" /> <entry offset=""0x64"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""16"" document=""1"" /> <entry offset=""0x65"" startLine=""19"" startColumn=""27"" endLine=""19"" endColumn=""51"" document=""1"" /> <entry offset=""0x7b"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""19"" startColumn=""18"" endLine=""19"" endColumn=""23"" document=""1"" /> <entry offset=""0x84"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""10"" document=""1"" /> <entry offset=""0x85"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""34"" document=""1"" /> <entry offset=""0x8d"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" hidden=""true"" document=""1"" /> <entry offset=""0x94"" startLine=""19"" startColumn=""24"" endLine=""19"" endColumn=""26"" document=""1"" /> <entry offset=""0x9c"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9d""> <namespace name=""System"" /> <scope startOffset=""0x18"" endOffset=""0x25""> <local name=""x"" il_index=""2"" il_start=""0x18"" il_end=""0x25"" attributes=""0"" /> </scope> <scope startOffset=""0x47"" endOffset=""0x57""> <local name=""x"" il_index=""5"" il_start=""0x47"" il_end=""0x57"" attributes=""0"" /> </scope> <scope startOffset=""0x7d"" endOffset=""0x8e""> <local name=""x"" il_index=""8"" il_start=""0x7d"" il_end=""0x8e"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void HiddenMethods() { var src = @" using System; class C { #line hidden public static void H() { F(); } #line default public static void G() { F(); } #line hidden public static void F() { { const int z = 1; var (x, y) = (1,2); Console.WriteLine(x + z); } { dynamic x = 1; Console.WriteLine(x); } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""13"" document=""1"" /> <entry offset=""0x7"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void HiddenEntryPoint() { var src = @" class C { #line hidden public static void Main() { } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugExe); // Note: Dev10 emitted a hidden sequence point to #line hidden method, // which enabled the debugger to locate the first user visible sequence point starting from the entry point. // Roslyn does not emit such sequence point. We could potentially synthesize one but that would defeat the purpose of // #line hidden directive. c.VerifyPdb(@" <symbols> <entryPoint declaringType=""C"" methodName=""Main"" /> <methods> <method containingType=""C"" name=""Main"" format=""windows""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> </method> </methods> </symbols>", // When converting from Portable to Windows the PDB writer doesn't create an entry for the Main method // and thus there is no entry point record either. options: PdbValidationOptions.SkipConversionValidation); } [Fact] public void HiddenIterator() { var src = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class C { public static void Main() { F(); } #line hidden public static IEnumerable<int> F() { { const int z = 1; var (x, y) = (1,2); Console.WriteLine(x + z); } { dynamic x = 1; Console.WriteLine(x); } yield return 1; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(src, references: new[] { CSharpRef, ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll); // We don't really need the debug info for kickoff method when the entire iterator method is hidden, // but it doesn't hurt and removing it would need extra effort that's unnecessary. c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> </scope> </method> <method containingType=""C"" name=""F""> <customDebugInfo> <forwardIterator name=""&lt;F&gt;d__1"" /> <encLocalSlotMap> <slot kind=""0"" offset=""61"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""158"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); } #endregion #region Nested Types [Fact] public void NestedTypes() { string source = WithWindowsLineBreaks(@" using System; namespace N { public class C { public class D<T> { public class E { public static void f(int a) { Console.WriteLine(); } } } } } "); var c = CreateCompilation(Parse(source, filename: "file.cs")); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""file.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""F7-03-46-2C-11-16-DE-85-F9-DD-5C-76-F6-55-D9-13-E0-95-DE-14"" /> </files> <methods> <method containingType=""N.C+D`1+E"" name=""f"" parameterNames=""a""> <customDebugInfo> <using> <namespace usingCount=""0"" /> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""6"" endLine=""14"" endColumn=""26"" document=""1"" /> <entry offset=""0x5"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } #endregion #region Expression Bodied Members [Fact] public void ExpressionBodiedProperty() { var source = WithWindowsLineBreaks(@" class C { public int P => M(); public int M() { return 2; } }"); var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""21"" endLine=""4"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_P"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""18"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public int this[Int32 i] => M(); public int M() { return 2; } }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""33"" endLine=""6"" endColumn=""36"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> </scope> </method> <method containingType=""C"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedMethod() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Int32 P => 2; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_P""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""23"" endLine=""6"" endColumn=""24"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedOperator() { var comp = CreateCompilationWithMscorlib45(@" class C { public static C operator ++(C c) => c; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""op_Increment"" parameterNames=""c""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""41"" endLine=""4"" endColumn=""42"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ExpressionBodiedConversion() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public static explicit operator C(Int32 i) => new C(); }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""op_Explicit"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""51"" endLine=""6"" endColumn=""58"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedConstructor() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public int X; public C(Int32 x) => X = x; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""26"" endLine=""7"" endColumn=""31"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedDestructor() { var comp = CreateCompilationWithMscorlib45(@" class C { public int X; ~C() => X = 0; }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Finalize""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""13"" endLine=""5"" endColumn=""18"" document=""1"" /> <entry offset=""0x9"" hidden=""true"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(14438, "https://github.com/dotnet/roslyn/issues/14438")] [Fact] public void ExpressionBodiedAccessor() { var comp = CreateCompilationWithMscorlib45(@" class C { public int x; public int X { get => x; set => x = value; } public event System.Action E { add => x = 1; remove => x = 0; } }"); comp.VerifyDiagnostics(); comp.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""get_X""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""16"" endLine=""7"" endColumn=""17"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""set_X"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""16"" endLine=""8"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""add_E"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""remove_E"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""C"" methodName=""get_X"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Synthesized Methods [Fact] public void ImportsInLambda() { var source = WithWindowsLineBreaks( @"using System.Collections.Generic; using System.Linq; class C { static void M() { System.Action f = () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; f(); } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<>c.<M>b__0_0", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> <encLocalSlotMap> <slot kind=""0"" offset=""63"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""30"" document=""1"" /> <entry offset=""0x39"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3a""> <local name=""c"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void ImportsInIterator() { var source = WithWindowsLineBreaks( @"using System.Collections.Generic; using System.Linq; class C { static IEnumerable<object> F() { var c = new[] { 1, 2, 3 }; foreach (var i in c.Select(i => i)) { yield return i; } } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<F>d__0.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c"" methodName=""&lt;F&gt;b__0_0"" parameterNames=""i"" /> <hoistedLocalScopes> <slot startOffset=""0x27"" endOffset=""0xd5"" /> <slot /> <slot startOffset=""0x7f"" endOffset=""0xb6"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""temp"" /> <slot kind=""27"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x27"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x28"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" /> <entry offset=""0x3f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x40"" startLine=""8"" startColumn=""27"" endLine=""8"" endColumn=""43"" document=""1"" /> <entry offset=""0x7d"" hidden=""true"" document=""1"" /> <entry offset=""0x7f"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""23"" document=""1"" /> <entry offset=""0x90"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x91"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""28"" document=""1"" /> <entry offset=""0xad"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0xb6"" startLine=""8"" startColumn=""24"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xd1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0xd5"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void ImportsInAsync() { var source = WithWindowsLineBreaks( @"using System.Linq; using System.Threading.Tasks; class C { static async Task F() { var c = new[] { 1, 2, 3 }; c.Select(i => i); } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<F>d__0.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;F&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C+&lt;&gt;c"" methodName=""&lt;F&gt;b__0_0"" parameterNames=""i"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x87"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""35"" document=""1"" /> <entry offset=""0x1f"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0x4c"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x73"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <kickoffMethod declaringType=""C"" methodName=""F"" /> </asyncInfo> </method> </methods> </symbols>"); } [WorkItem(2501, "https://github.com/dotnet/roslyn/issues/2501")] [Fact] public void ImportsInAsyncLambda() { var source = WithWindowsLineBreaks( @"using System.Linq; class C { static void M() { System.Action f = async () => { var c = new[] { 1, 2, 3 }; c.Select(i => i); }; } }"); var c = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, references: new[] { SystemCoreRef }); c.VerifyPdb("C+<>c.<M>b__0_0", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;M&gt;b__0_0""> <customDebugInfo> <forwardIterator name=""&lt;&lt;M&gt;b__0_0&gt;d"" /> <encLocalSlotMap> <slot kind=""0"" offset=""69"" /> </encLocalSlotMap> </customDebugInfo> </method> </methods> </symbols>"); c.VerifyPdb("C+<>c+<<M>b__0_0>d.MoveNext", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c+&lt;&lt;M&gt;b__0_0&gt;d"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""C"" methodName=""M"" /> <hoistedLocalScopes> <slot startOffset=""0x0"" endOffset=""0x87"" /> </hoistedLocalScopes> <encLocalSlotMap> <slot kind=""27"" offset=""50"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""39"" document=""1"" /> <entry offset=""0x1f"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x4c"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0x4c"" /> <kickoffMethod declaringType=""C+&lt;&gt;c"" methodName=""&lt;M&gt;b__0_0"" /> </asyncInfo> </method> </methods> </symbols>"); } #endregion #region Patterns [Fact] public void SyntaxOffset_IsPattern() { var source = @"class C { bool F(object o) => o is int i && o is 3 && o is bool; }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""31"" endLine=""1"" endColumn=""64"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2d""> <local name=""i"" il_index=""0"" il_start=""0x0"" il_end=""0x2d"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchStatement() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static int Main() { switch (F()) { // declaration pattern case int x when G(x) > 10: return 1; // discard pattern case bool _: return 2; // var pattern case var (y, z): return 3; // constant pattern case 4.0: return 4; // positional patterns case C() when B(): return 5; case (): return 6; case C(int p, C(int q)): return 7; case C(x: int p): return 8; // property pattern case D { P: 1, Q: D { P: 2 }, R: C(int z) }: return 9; default: return 10; }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @" { // Code size 432 (0x1b0) .maxstack 3 .locals init (int V_0, //x object V_1, //y object V_2, //z int V_3, //p int V_4, //q int V_5, //p int V_6, //z object V_7, System.Runtime.CompilerServices.ITuple V_8, int V_9, double V_10, C V_11, object V_12, C V_13, D V_14, int V_15, D V_16, int V_17, C V_18, object V_19, int V_20) // sequence point: { IL_0000: nop // sequence point: switch (F()) IL_0001: call ""object Program.F()"" IL_0006: stloc.s V_19 // sequence point: <hidden> IL_0008: ldloc.s V_19 IL_000a: stloc.s V_7 // sequence point: <hidden> IL_000c: ldloc.s V_7 IL_000e: isinst ""int"" IL_0013: brfalse.s IL_0022 IL_0015: ldloc.s V_7 IL_0017: unbox.any ""int"" IL_001c: stloc.0 // sequence point: <hidden> IL_001d: br IL_014d IL_0022: ldloc.s V_7 IL_0024: isinst ""bool"" IL_0029: brtrue IL_015e IL_002e: ldloc.s V_7 IL_0030: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0035: stloc.s V_8 IL_0037: ldloc.s V_8 IL_0039: brfalse.s IL_0080 IL_003b: ldloc.s V_8 IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0042: stloc.s V_9 // sequence point: <hidden> IL_0044: ldloc.s V_9 IL_0046: ldc.i4.2 IL_0047: bne.un.s IL_0060 IL_0049: ldloc.s V_8 IL_004b: ldc.i4.0 IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0051: stloc.1 // sequence point: <hidden> IL_0052: ldloc.s V_8 IL_0054: ldc.i4.1 IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_005a: stloc.2 // sequence point: <hidden> IL_005b: br IL_0163 IL_0060: ldloc.s V_7 IL_0062: isinst ""C"" IL_0067: brtrue IL_016f IL_006c: br.s IL_0077 IL_006e: ldloc.s V_9 IL_0070: brfalse IL_018c IL_0075: br.s IL_00b5 IL_0077: ldloc.s V_9 IL_0079: brfalse IL_018c IL_007e: br.s IL_00f5 IL_0080: ldloc.s V_7 IL_0082: isinst ""double"" IL_0087: brfalse.s IL_00a7 IL_0089: ldloc.s V_7 IL_008b: unbox.any ""double"" IL_0090: stloc.s V_10 // sequence point: <hidden> IL_0092: ldloc.s V_10 IL_0094: ldc.r8 4 IL_009d: beq IL_016a IL_00a2: br IL_01a7 IL_00a7: ldloc.s V_7 IL_00a9: isinst ""C"" IL_00ae: brtrue IL_017b IL_00b3: br.s IL_00f5 IL_00b5: ldloc.s V_7 IL_00b7: castclass ""C"" IL_00bc: stloc.s V_11 // sequence point: <hidden> IL_00be: ldloc.s V_11 IL_00c0: ldloca.s V_3 IL_00c2: ldloca.s V_12 IL_00c4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00c9: nop // sequence point: <hidden> IL_00ca: ldloc.s V_12 IL_00cc: isinst ""C"" IL_00d1: stloc.s V_13 IL_00d3: ldloc.s V_13 IL_00d5: brfalse.s IL_00e6 IL_00d7: ldloc.s V_13 IL_00d9: ldloca.s V_4 IL_00db: callvirt ""void C.Deconstruct(out int)"" IL_00e0: nop // sequence point: <hidden> IL_00e1: br IL_0191 IL_00e6: ldloc.s V_11 IL_00e8: ldloca.s V_5 IL_00ea: callvirt ""void C.Deconstruct(out int)"" IL_00ef: nop // sequence point: <hidden> IL_00f0: br IL_0198 IL_00f5: ldloc.s V_7 IL_00f7: isinst ""D"" IL_00fc: stloc.s V_14 IL_00fe: ldloc.s V_14 IL_0100: brfalse IL_01a7 IL_0105: ldloc.s V_14 IL_0107: callvirt ""int D.P.get"" IL_010c: stloc.s V_15 // sequence point: <hidden> IL_010e: ldloc.s V_15 IL_0110: ldc.i4.1 IL_0111: bne.un IL_01a7 IL_0116: ldloc.s V_14 IL_0118: callvirt ""D D.Q.get"" IL_011d: stloc.s V_16 // sequence point: <hidden> IL_011f: ldloc.s V_16 IL_0121: brfalse IL_01a7 IL_0126: ldloc.s V_16 IL_0128: callvirt ""int D.P.get"" IL_012d: stloc.s V_17 // sequence point: <hidden> IL_012f: ldloc.s V_17 IL_0131: ldc.i4.2 IL_0132: bne.un.s IL_01a7 IL_0134: ldloc.s V_14 IL_0136: callvirt ""C D.R.get"" IL_013b: stloc.s V_18 // sequence point: <hidden> IL_013d: ldloc.s V_18 IL_013f: brfalse.s IL_01a7 IL_0141: ldloc.s V_18 IL_0143: ldloca.s V_6 IL_0145: callvirt ""void C.Deconstruct(out int)"" IL_014a: nop // sequence point: <hidden> IL_014b: br.s IL_019f // sequence point: when G(x) > 10 IL_014d: ldloc.0 IL_014e: call ""int Program.G(int)"" IL_0153: ldc.i4.s 10 IL_0155: bgt.s IL_0159 // sequence point: <hidden> IL_0157: br.s IL_01a7 // sequence point: return 1; IL_0159: ldc.i4.1 IL_015a: stloc.s V_20 IL_015c: br.s IL_01ad // sequence point: return 2; IL_015e: ldc.i4.2 IL_015f: stloc.s V_20 IL_0161: br.s IL_01ad // sequence point: <hidden> IL_0163: br.s IL_0165 // sequence point: return 3; IL_0165: ldc.i4.3 IL_0166: stloc.s V_20 IL_0168: br.s IL_01ad // sequence point: return 4; IL_016a: ldc.i4.4 IL_016b: stloc.s V_20 IL_016d: br.s IL_01ad // sequence point: when B() IL_016f: call ""bool Program.B()"" IL_0174: brtrue.s IL_0187 // sequence point: <hidden> IL_0176: br IL_006e // sequence point: when B() IL_017b: call ""bool Program.B()"" IL_0180: brtrue.s IL_0187 // sequence point: <hidden> IL_0182: br IL_00b5 // sequence point: return 5; IL_0187: ldc.i4.5 IL_0188: stloc.s V_20 IL_018a: br.s IL_01ad // sequence point: return 6; IL_018c: ldc.i4.6 IL_018d: stloc.s V_20 IL_018f: br.s IL_01ad // sequence point: <hidden> IL_0191: br.s IL_0193 // sequence point: return 7; IL_0193: ldc.i4.7 IL_0194: stloc.s V_20 IL_0196: br.s IL_01ad // sequence point: <hidden> IL_0198: br.s IL_019a // sequence point: return 8; IL_019a: ldc.i4.8 IL_019b: stloc.s V_20 IL_019d: br.s IL_01ad // sequence point: <hidden> IL_019f: br.s IL_01a1 // sequence point: return 9; IL_01a1: ldc.i4.s 9 IL_01a3: stloc.s V_20 IL_01a5: br.s IL_01ad // sequence point: return 10; IL_01a7: ldc.i4.s 10 IL_01a9: stloc.s V_20 IL_01ab: br.s IL_01ad // sequence point: } IL_01ad: ldloc.s V_20 IL_01af: ret } ", source: source); verifier.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""93"" /> <slot kind=""0"" offset=""244"" /> <slot kind=""0"" offset=""247"" /> <slot kind=""0"" offset=""465"" /> <slot kind=""0"" offset=""474"" /> <slot kind=""0"" offset=""516"" /> <slot kind=""0"" offset=""617"" /> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""35"" offset=""11"" ordinal=""2"" /> <slot kind=""35"" offset=""11"" ordinal=""3"" /> <slot kind=""35"" offset=""11"" ordinal=""4"" /> <slot kind=""35"" offset=""11"" ordinal=""5"" /> <slot kind=""35"" offset=""11"" ordinal=""6"" /> <slot kind=""35"" offset=""11"" ordinal=""7"" /> <slot kind=""35"" offset=""11"" ordinal=""8"" /> <slot kind=""35"" offset=""11"" ordinal=""9"" /> <slot kind=""35"" offset=""11"" ordinal=""10"" /> <slot kind=""35"" offset=""11"" ordinal=""11"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""21"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> <entry offset=""0x52"" hidden=""true"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" hidden=""true"" document=""1"" /> <entry offset=""0xf0"" hidden=""true"" document=""1"" /> <entry offset=""0x10e"" hidden=""true"" document=""1"" /> <entry offset=""0x11f"" hidden=""true"" document=""1"" /> <entry offset=""0x12f"" hidden=""true"" document=""1"" /> <entry offset=""0x13d"" hidden=""true"" document=""1"" /> <entry offset=""0x14b"" hidden=""true"" document=""1"" /> <entry offset=""0x14d"" startLine=""27"" startColumn=""24"" endLine=""27"" endColumn=""38"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""27"" startColumn=""40"" endLine=""27"" endColumn=""49"" document=""1"" /> <entry offset=""0x15e"" startLine=""30"" startColumn=""26"" endLine=""30"" endColumn=""35"" document=""1"" /> <entry offset=""0x163"" hidden=""true"" document=""1"" /> <entry offset=""0x165"" startLine=""33"" startColumn=""30"" endLine=""33"" endColumn=""39"" document=""1"" /> <entry offset=""0x16a"" startLine=""36"" startColumn=""23"" endLine=""36"" endColumn=""32"" document=""1"" /> <entry offset=""0x16f"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x176"" hidden=""true"" document=""1"" /> <entry offset=""0x17b"" startLine=""39"" startColumn=""22"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x182"" hidden=""true"" document=""1"" /> <entry offset=""0x187"" startLine=""39"" startColumn=""32"" endLine=""39"" endColumn=""41"" document=""1"" /> <entry offset=""0x18c"" startLine=""40"" startColumn=""22"" endLine=""40"" endColumn=""31"" document=""1"" /> <entry offset=""0x191"" hidden=""true"" document=""1"" /> <entry offset=""0x193"" startLine=""41"" startColumn=""38"" endLine=""41"" endColumn=""47"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19a"" startLine=""42"" startColumn=""31"" endLine=""42"" endColumn=""40"" document=""1"" /> <entry offset=""0x19f"" hidden=""true"" document=""1"" /> <entry offset=""0x1a1"" startLine=""45"" startColumn=""58"" endLine=""45"" endColumn=""67"" document=""1"" /> <entry offset=""0x1a7"" startLine=""47"" startColumn=""22"" endLine=""47"" endColumn=""32"" document=""1"" /> <entry offset=""0x1ad"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b0""> <scope startOffset=""0x14d"" endOffset=""0x15e""> <local name=""x"" il_index=""0"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" /> </scope> <scope startOffset=""0x163"" endOffset=""0x16a""> <local name=""y"" il_index=""1"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> <local name=""z"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> </scope> <scope startOffset=""0x191"" endOffset=""0x198""> <local name=""p"" il_index=""3"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> <local name=""q"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> </scope> <scope startOffset=""0x198"" endOffset=""0x19f""> <local name=""p"" il_index=""5"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" /> </scope> <scope startOffset=""0x19f"" endOffset=""0x1a7""> <local name=""z"" il_index=""6"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchExpression() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static void Main() { var a = F() switch { // declaration pattern int x when G(x) > 10 => 1, // discard pattern bool _ => 2, // var pattern var (y, z) => 3, // constant pattern 4.0 => 4, // positional patterns C() when B() => 5, () => 6, C(int p, C(int q)) => 7, C(x: int p) => 8, // property pattern D { P: 1, Q: D { P: 2 }, R: C (int z) } => 9, _ => 10, }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); // note no sequence points emitted within the switch expression verifier.VerifyIL("Program.Main", sequencePoints: "Program.Main", expectedIL: @" { // Code size 437 (0x1b5) .maxstack 3 .locals init (int V_0, //a int V_1, //x object V_2, //y object V_3, //z int V_4, //p int V_5, //q int V_6, //p int V_7, //z int V_8, object V_9, System.Runtime.CompilerServices.ITuple V_10, int V_11, double V_12, C V_13, object V_14, C V_15, D V_16, int V_17, D V_18, int V_19, C V_20) -IL_0000: nop -IL_0001: call ""object Program.F()"" IL_0006: stloc.s V_9 IL_0008: ldc.i4.1 IL_0009: brtrue.s IL_000c -IL_000b: nop ~IL_000c: ldloc.s V_9 IL_000e: isinst ""int"" IL_0013: brfalse.s IL_0022 IL_0015: ldloc.s V_9 IL_0017: unbox.any ""int"" IL_001c: stloc.1 ~IL_001d: br IL_014d IL_0022: ldloc.s V_9 IL_0024: isinst ""bool"" IL_0029: brtrue IL_015e IL_002e: ldloc.s V_9 IL_0030: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0035: stloc.s V_10 IL_0037: ldloc.s V_10 IL_0039: brfalse.s IL_0080 IL_003b: ldloc.s V_10 IL_003d: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0042: stloc.s V_11 ~IL_0044: ldloc.s V_11 IL_0046: ldc.i4.2 IL_0047: bne.un.s IL_0060 IL_0049: ldloc.s V_10 IL_004b: ldc.i4.0 IL_004c: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0051: stloc.2 ~IL_0052: ldloc.s V_10 IL_0054: ldc.i4.1 IL_0055: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_005a: stloc.3 ~IL_005b: br IL_0163 IL_0060: ldloc.s V_9 IL_0062: isinst ""C"" IL_0067: brtrue IL_016f IL_006c: br.s IL_0077 IL_006e: ldloc.s V_11 IL_0070: brfalse IL_018c IL_0075: br.s IL_00b5 IL_0077: ldloc.s V_11 IL_0079: brfalse IL_018c IL_007e: br.s IL_00f5 IL_0080: ldloc.s V_9 IL_0082: isinst ""double"" IL_0087: brfalse.s IL_00a7 IL_0089: ldloc.s V_9 IL_008b: unbox.any ""double"" IL_0090: stloc.s V_12 ~IL_0092: ldloc.s V_12 IL_0094: ldc.r8 4 IL_009d: beq IL_016a IL_00a2: br IL_01a7 IL_00a7: ldloc.s V_9 IL_00a9: isinst ""C"" IL_00ae: brtrue IL_017b IL_00b3: br.s IL_00f5 IL_00b5: ldloc.s V_9 IL_00b7: castclass ""C"" IL_00bc: stloc.s V_13 ~IL_00be: ldloc.s V_13 IL_00c0: ldloca.s V_4 IL_00c2: ldloca.s V_14 IL_00c4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00c9: nop ~IL_00ca: ldloc.s V_14 IL_00cc: isinst ""C"" IL_00d1: stloc.s V_15 IL_00d3: ldloc.s V_15 IL_00d5: brfalse.s IL_00e6 IL_00d7: ldloc.s V_15 IL_00d9: ldloca.s V_5 IL_00db: callvirt ""void C.Deconstruct(out int)"" IL_00e0: nop ~IL_00e1: br IL_0191 IL_00e6: ldloc.s V_13 IL_00e8: ldloca.s V_6 IL_00ea: callvirt ""void C.Deconstruct(out int)"" IL_00ef: nop ~IL_00f0: br IL_0198 IL_00f5: ldloc.s V_9 IL_00f7: isinst ""D"" IL_00fc: stloc.s V_16 IL_00fe: ldloc.s V_16 IL_0100: brfalse IL_01a7 IL_0105: ldloc.s V_16 IL_0107: callvirt ""int D.P.get"" IL_010c: stloc.s V_17 ~IL_010e: ldloc.s V_17 IL_0110: ldc.i4.1 IL_0111: bne.un IL_01a7 IL_0116: ldloc.s V_16 IL_0118: callvirt ""D D.Q.get"" IL_011d: stloc.s V_18 ~IL_011f: ldloc.s V_18 IL_0121: brfalse IL_01a7 IL_0126: ldloc.s V_18 IL_0128: callvirt ""int D.P.get"" IL_012d: stloc.s V_19 ~IL_012f: ldloc.s V_19 IL_0131: ldc.i4.2 IL_0132: bne.un.s IL_01a7 IL_0134: ldloc.s V_16 IL_0136: callvirt ""C D.R.get"" IL_013b: stloc.s V_20 ~IL_013d: ldloc.s V_20 IL_013f: brfalse.s IL_01a7 IL_0141: ldloc.s V_20 IL_0143: ldloca.s V_7 IL_0145: callvirt ""void C.Deconstruct(out int)"" IL_014a: nop ~IL_014b: br.s IL_019f -IL_014d: ldloc.1 IL_014e: call ""int Program.G(int)"" IL_0153: ldc.i4.s 10 IL_0155: bgt.s IL_0159 ~IL_0157: br.s IL_01a7 -IL_0159: ldc.i4.1 IL_015a: stloc.s V_8 IL_015c: br.s IL_01ad -IL_015e: ldc.i4.2 IL_015f: stloc.s V_8 IL_0161: br.s IL_01ad ~IL_0163: br.s IL_0165 -IL_0165: ldc.i4.3 IL_0166: stloc.s V_8 IL_0168: br.s IL_01ad -IL_016a: ldc.i4.4 IL_016b: stloc.s V_8 IL_016d: br.s IL_01ad -IL_016f: call ""bool Program.B()"" IL_0174: brtrue.s IL_0187 ~IL_0176: br IL_006e -IL_017b: call ""bool Program.B()"" IL_0180: brtrue.s IL_0187 ~IL_0182: br IL_00b5 -IL_0187: ldc.i4.5 IL_0188: stloc.s V_8 IL_018a: br.s IL_01ad -IL_018c: ldc.i4.6 IL_018d: stloc.s V_8 IL_018f: br.s IL_01ad ~IL_0191: br.s IL_0193 -IL_0193: ldc.i4.7 IL_0194: stloc.s V_8 IL_0196: br.s IL_01ad ~IL_0198: br.s IL_019a -IL_019a: ldc.i4.8 IL_019b: stloc.s V_8 IL_019d: br.s IL_01ad ~IL_019f: br.s IL_01a1 -IL_01a1: ldc.i4.s 9 IL_01a3: stloc.s V_8 IL_01a5: br.s IL_01ad -IL_01a7: ldc.i4.s 10 IL_01a9: stloc.s V_8 IL_01ab: br.s IL_01ad ~IL_01ad: ldc.i4.1 IL_01ae: brtrue.s IL_01b1 -IL_01b0: nop ~IL_01b1: ldloc.s V_8 IL_01b3: stloc.0 -IL_01b4: ret } "); verifier.VerifyPdb("Program.Main", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""94"" /> <slot kind=""0"" offset=""225"" /> <slot kind=""0"" offset=""228"" /> <slot kind=""0"" offset=""406"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""447"" /> <slot kind=""0"" offset=""539"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""23"" /> <slot kind=""35"" offset=""23"" ordinal=""1"" /> <slot kind=""35"" offset=""23"" ordinal=""2"" /> <slot kind=""35"" offset=""23"" ordinal=""3"" /> <slot kind=""35"" offset=""23"" ordinal=""4"" /> <slot kind=""35"" offset=""23"" ordinal=""5"" /> <slot kind=""35"" offset=""23"" ordinal=""6"" /> <slot kind=""35"" offset=""23"" ordinal=""7"" /> <slot kind=""35"" offset=""23"" ordinal=""8"" /> <slot kind=""35"" offset=""23"" ordinal=""9"" /> <slot kind=""35"" offset=""23"" ordinal=""10"" /> <slot kind=""35"" offset=""23"" ordinal=""11"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" /> <entry offset=""0xb"" startLine=""24"" startColumn=""21"" endLine=""48"" endColumn=""10"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x44"" hidden=""true"" document=""1"" /> <entry offset=""0x52"" hidden=""true"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x92"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" hidden=""true"" document=""1"" /> <entry offset=""0xe1"" hidden=""true"" document=""1"" /> <entry offset=""0xf0"" hidden=""true"" document=""1"" /> <entry offset=""0x10e"" hidden=""true"" document=""1"" /> <entry offset=""0x11f"" hidden=""true"" document=""1"" /> <entry offset=""0x12f"" hidden=""true"" document=""1"" /> <entry offset=""0x13d"" hidden=""true"" document=""1"" /> <entry offset=""0x14b"" hidden=""true"" document=""1"" /> <entry offset=""0x14d"" startLine=""27"" startColumn=""19"" endLine=""27"" endColumn=""33"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""27"" startColumn=""37"" endLine=""27"" endColumn=""38"" document=""1"" /> <entry offset=""0x15e"" startLine=""30"" startColumn=""23"" endLine=""30"" endColumn=""24"" document=""1"" /> <entry offset=""0x163"" hidden=""true"" document=""1"" /> <entry offset=""0x165"" startLine=""33"" startColumn=""27"" endLine=""33"" endColumn=""28"" document=""1"" /> <entry offset=""0x16a"" startLine=""36"" startColumn=""20"" endLine=""36"" endColumn=""21"" document=""1"" /> <entry offset=""0x16f"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" /> <entry offset=""0x176"" hidden=""true"" document=""1"" /> <entry offset=""0x17b"" startLine=""39"" startColumn=""17"" endLine=""39"" endColumn=""25"" document=""1"" /> <entry offset=""0x182"" hidden=""true"" document=""1"" /> <entry offset=""0x187"" startLine=""39"" startColumn=""29"" endLine=""39"" endColumn=""30"" document=""1"" /> <entry offset=""0x18c"" startLine=""40"" startColumn=""19"" endLine=""40"" endColumn=""20"" document=""1"" /> <entry offset=""0x191"" hidden=""true"" document=""1"" /> <entry offset=""0x193"" startLine=""41"" startColumn=""35"" endLine=""41"" endColumn=""36"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19a"" startLine=""42"" startColumn=""28"" endLine=""42"" endColumn=""29"" document=""1"" /> <entry offset=""0x19f"" hidden=""true"" document=""1"" /> <entry offset=""0x1a1"" startLine=""45"" startColumn=""56"" endLine=""45"" endColumn=""57"" document=""1"" /> <entry offset=""0x1a7"" startLine=""47"" startColumn=""18"" endLine=""47"" endColumn=""20"" document=""1"" /> <entry offset=""0x1ad"" hidden=""true"" document=""1"" /> <entry offset=""0x1b0"" startLine=""24"" startColumn=""9"" endLine=""48"" endColumn=""11"" document=""1"" /> <entry offset=""0x1b1"" hidden=""true"" document=""1"" /> <entry offset=""0x1b4"" startLine=""49"" startColumn=""5"" endLine=""49"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b5""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b5"" attributes=""0"" /> <scope startOffset=""0x14d"" endOffset=""0x15e""> <local name=""x"" il_index=""1"" il_start=""0x14d"" il_end=""0x15e"" attributes=""0"" /> </scope> <scope startOffset=""0x163"" endOffset=""0x16a""> <local name=""y"" il_index=""2"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> <local name=""z"" il_index=""3"" il_start=""0x163"" il_end=""0x16a"" attributes=""0"" /> </scope> <scope startOffset=""0x191"" endOffset=""0x198""> <local name=""p"" il_index=""4"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> <local name=""q"" il_index=""5"" il_start=""0x191"" il_end=""0x198"" attributes=""0"" /> </scope> <scope startOffset=""0x198"" endOffset=""0x19f""> <local name=""p"" il_index=""6"" il_start=""0x198"" il_end=""0x19f"" attributes=""0"" /> </scope> <scope startOffset=""0x19f"" endOffset=""0x1a7""> <local name=""z"" il_index=""7"" il_start=""0x19f"" il_end=""0x1a7"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_IsPattern() { string source = WithWindowsLineBreaks(@" class C { public void Deconstruct() { } public void Deconstruct(out int x) { x = 1; } public void Deconstruct(out int x, out object y) { x = 2; y = new C(); } } class D { public int P { get; set; } public D Q { get; set; } public C R { get; set; } } class Program { static object F() => new C(); static bool B() => true; static int G(int x) => x; static bool M() { object obj = F(); return // declaration pattern obj is int x || // discard pattern obj is bool _ || // var pattern obj is var (y, z1) || // constant pattern obj is 4.0 || // positional patterns obj is C() || obj is () || obj is C(int p1, C(int q)) || obj is C(x: int p2) || // property pattern obj is D { P: 1, Q: D { P: 2 }, R: C(int z2) }; } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(c, verify: Verification.Skipped); verifier.VerifyIL("Program.M", sequencePoints: "Program.M", expectedIL: @" { // Code size 301 (0x12d) .maxstack 3 .locals init (object V_0, //obj int V_1, //x object V_2, //y object V_3, //z1 int V_4, //p1 int V_5, //q int V_6, //p2 int V_7, //z2 System.Runtime.CompilerServices.ITuple V_8, C V_9, object V_10, C V_11, D V_12, D V_13, bool V_14) -IL_0000: nop -IL_0001: call ""object Program.F()"" IL_0006: stloc.0 -IL_0007: ldloc.0 IL_0008: isinst ""int"" IL_000d: brfalse.s IL_001b IL_000f: ldloc.0 IL_0010: unbox.any ""int"" IL_0015: stloc.1 IL_0016: br IL_0125 IL_001b: ldloc.0 IL_001c: isinst ""bool"" IL_0021: brtrue IL_0125 IL_0026: ldloc.0 IL_0027: isinst ""System.Runtime.CompilerServices.ITuple"" IL_002c: stloc.s V_8 IL_002e: ldloc.s V_8 IL_0030: brfalse.s IL_0053 IL_0032: ldloc.s V_8 IL_0034: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_0039: ldc.i4.2 IL_003a: bne.un.s IL_0053 IL_003c: ldloc.s V_8 IL_003e: ldc.i4.0 IL_003f: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_0044: stloc.2 IL_0045: ldloc.s V_8 IL_0047: ldc.i4.1 IL_0048: callvirt ""object System.Runtime.CompilerServices.ITuple.this[int].get"" IL_004d: stloc.3 IL_004e: br IL_0125 IL_0053: ldloc.0 IL_0054: isinst ""double"" IL_0059: brfalse.s IL_006f IL_005b: ldloc.0 IL_005c: unbox.any ""double"" IL_0061: ldc.r8 4 IL_006a: beq IL_0125 IL_006f: ldloc.0 IL_0070: isinst ""C"" IL_0075: brtrue IL_0125 IL_007a: ldloc.0 IL_007b: isinst ""System.Runtime.CompilerServices.ITuple"" IL_0080: stloc.s V_8 IL_0082: ldloc.s V_8 IL_0084: brfalse.s IL_0092 IL_0086: ldloc.s V_8 IL_0088: callvirt ""int System.Runtime.CompilerServices.ITuple.Length.get"" IL_008d: brfalse IL_0125 IL_0092: ldloc.0 IL_0093: isinst ""C"" IL_0098: stloc.s V_9 IL_009a: ldloc.s V_9 IL_009c: brfalse.s IL_00c3 IL_009e: ldloc.s V_9 IL_00a0: ldloca.s V_4 IL_00a2: ldloca.s V_10 IL_00a4: callvirt ""void C.Deconstruct(out int, out object)"" IL_00a9: nop IL_00aa: ldloc.s V_10 IL_00ac: isinst ""C"" IL_00b1: stloc.s V_11 IL_00b3: ldloc.s V_11 IL_00b5: brfalse.s IL_00c3 IL_00b7: ldloc.s V_11 IL_00b9: ldloca.s V_5 IL_00bb: callvirt ""void C.Deconstruct(out int)"" IL_00c0: nop IL_00c1: br.s IL_0125 IL_00c3: ldloc.0 IL_00c4: isinst ""C"" IL_00c9: stloc.s V_11 IL_00cb: ldloc.s V_11 IL_00cd: brfalse.s IL_00db IL_00cf: ldloc.s V_11 IL_00d1: ldloca.s V_6 IL_00d3: callvirt ""void C.Deconstruct(out int)"" IL_00d8: nop IL_00d9: br.s IL_0125 IL_00db: ldloc.0 IL_00dc: isinst ""D"" IL_00e1: stloc.s V_12 IL_00e3: ldloc.s V_12 IL_00e5: brfalse.s IL_0122 IL_00e7: ldloc.s V_12 IL_00e9: callvirt ""int D.P.get"" IL_00ee: ldc.i4.1 IL_00ef: bne.un.s IL_0122 IL_00f1: ldloc.s V_12 IL_00f3: callvirt ""D D.Q.get"" IL_00f8: stloc.s V_13 IL_00fa: ldloc.s V_13 IL_00fc: brfalse.s IL_0122 IL_00fe: ldloc.s V_13 IL_0100: callvirt ""int D.P.get"" IL_0105: ldc.i4.2 IL_0106: bne.un.s IL_0122 IL_0108: ldloc.s V_12 IL_010a: callvirt ""C D.R.get"" IL_010f: stloc.s V_11 IL_0111: ldloc.s V_11 IL_0113: brfalse.s IL_0122 IL_0115: ldloc.s V_11 IL_0117: ldloca.s V_7 IL_0119: callvirt ""void C.Deconstruct(out int)"" IL_011e: nop IL_011f: ldc.i4.1 IL_0120: br.s IL_0123 IL_0122: ldc.i4.0 IL_0123: br.s IL_0126 IL_0125: ldc.i4.1 IL_0126: stloc.s V_14 IL_0128: br.s IL_012a -IL_012a: ldloc.s V_14 IL_012c: ret } "); verifier.VerifyPdb("Program.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""M""> <customDebugInfo> <forward declaringType=""C"" methodName=""Deconstruct"" /> <encLocalSlotMap> <slot kind=""0"" offset=""18"" /> <slot kind=""0"" offset=""106"" /> <slot kind=""0"" offset=""230"" /> <slot kind=""0"" offset=""233"" /> <slot kind=""0"" offset=""419"" /> <slot kind=""0"" offset=""429"" /> <slot kind=""0"" offset=""465"" /> <slot kind=""0"" offset=""561"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""5"" endLine=""23"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""26"" document=""1"" /> <entry offset=""0x7"" startLine=""25"" startColumn=""9"" endLine=""45"" endColumn=""60"" document=""1"" /> <entry offset=""0x12a"" startLine=""46"" startColumn=""5"" endLine=""46"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x12d""> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""y"" il_index=""2"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""z1"" il_index=""3"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""p1"" il_index=""4"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""q"" il_index=""5"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""p2"" il_index=""6"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> <local name=""z2"" il_index=""7"" il_start=""0x0"" il_end=""0x12d"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(37232, "https://github.com/dotnet/roslyn/issues/37232")] [WorkItem(37237, "https://github.com/dotnet/roslyn/issues/37237")] [Fact] public void Patterns_SwitchExpression_Closures() { string source = WithWindowsLineBreaks(@" using System; public class C { static int M() { return F() switch { 1 => F() switch { C { P: int p, Q: C { P: int q } } => G(() => p + q), _ => 10 }, 2 => F() switch { C { P: int r } => G(() => r), _ => 20 }, C { Q: int s } => G(() => s), _ => 0 } switch { var t when t > 0 => G(() => t), _ => 0 }; } object P { get; set; } object Q { get; set; } static object F() => null; static int G(Func<int> f) => 0; } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 472 (0x1d8) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1, C.<>c__DisplayClass0_1 V_2, //CS$<>8__locals1 int V_3, object V_4, int V_5, C V_6, object V_7, C.<>c__DisplayClass0_2 V_8, //CS$<>8__locals2 int V_9, object V_10, C V_11, object V_12, object V_13, C V_14, object V_15, C.<>c__DisplayClass0_3 V_16, //CS$<>8__locals3 object V_17, C V_18, object V_19, int V_20) // sequence point: { IL_0000: nop // sequence point: <hidden> IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0006: stloc.0 // sequence point: <hidden> IL_0007: newobj ""C.<>c__DisplayClass0_1..ctor()"" IL_000c: stloc.2 IL_000d: call ""object C.F()"" IL_0012: stloc.s V_4 IL_0014: ldc.i4.1 IL_0015: brtrue.s IL_0018 // sequence point: switch ... } IL_0017: nop // sequence point: <hidden> IL_0018: ldloc.s V_4 IL_001a: isinst ""int"" IL_001f: brfalse.s IL_003e IL_0021: ldloc.s V_4 IL_0023: unbox.any ""int"" IL_0028: stloc.s V_5 // sequence point: <hidden> IL_002a: ldloc.s V_5 IL_002c: ldc.i4.1 IL_002d: beq.s IL_0075 IL_002f: br.s IL_0031 IL_0031: ldloc.s V_5 IL_0033: ldc.i4.2 IL_0034: beq IL_0116 IL_0039: br IL_0194 IL_003e: ldloc.s V_4 IL_0040: isinst ""C"" IL_0045: stloc.s V_6 IL_0047: ldloc.s V_6 IL_0049: brfalse IL_0194 IL_004e: ldloc.s V_6 IL_0050: callvirt ""object C.Q.get"" IL_0055: stloc.s V_7 // sequence point: <hidden> IL_0057: ldloc.s V_7 IL_0059: isinst ""int"" IL_005e: brfalse IL_0194 IL_0063: ldloc.2 IL_0064: ldloc.s V_7 IL_0066: unbox.any ""int"" IL_006b: stfld ""int C.<>c__DisplayClass0_1.<s>5__3"" // sequence point: <hidden> IL_0070: br IL_017e // sequence point: <hidden> IL_0075: newobj ""C.<>c__DisplayClass0_2..ctor()"" IL_007a: stloc.s V_8 IL_007c: call ""object C.F()"" IL_0081: stloc.s V_10 IL_0083: ldc.i4.1 IL_0084: brtrue.s IL_0087 // sequence point: switch ... IL_0086: nop // sequence point: <hidden> IL_0087: ldloc.s V_10 IL_0089: isinst ""C"" IL_008e: stloc.s V_11 IL_0090: ldloc.s V_11 IL_0092: brfalse.s IL_0104 IL_0094: ldloc.s V_11 IL_0096: callvirt ""object C.P.get"" IL_009b: stloc.s V_12 // sequence point: <hidden> IL_009d: ldloc.s V_12 IL_009f: isinst ""int"" IL_00a4: brfalse.s IL_0104 IL_00a6: ldloc.s V_8 IL_00a8: ldloc.s V_12 IL_00aa: unbox.any ""int"" IL_00af: stfld ""int C.<>c__DisplayClass0_2.<p>5__4"" // sequence point: <hidden> IL_00b4: ldloc.s V_11 IL_00b6: callvirt ""object C.Q.get"" IL_00bb: stloc.s V_13 // sequence point: <hidden> IL_00bd: ldloc.s V_13 IL_00bf: isinst ""C"" IL_00c4: stloc.s V_14 IL_00c6: ldloc.s V_14 IL_00c8: brfalse.s IL_0104 IL_00ca: ldloc.s V_14 IL_00cc: callvirt ""object C.P.get"" IL_00d1: stloc.s V_15 // sequence point: <hidden> IL_00d3: ldloc.s V_15 IL_00d5: isinst ""int"" IL_00da: brfalse.s IL_0104 IL_00dc: ldloc.s V_8 IL_00de: ldloc.s V_15 IL_00e0: unbox.any ""int"" IL_00e5: stfld ""int C.<>c__DisplayClass0_2.<q>5__5"" // sequence point: <hidden> IL_00ea: br.s IL_00ec // sequence point: <hidden> IL_00ec: br.s IL_00ee // sequence point: G(() => p + q) IL_00ee: ldloc.s V_8 IL_00f0: ldftn ""int C.<>c__DisplayClass0_2.<M>b__2()"" IL_00f6: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_00fb: call ""int C.G(System.Func<int>)"" IL_0100: stloc.s V_9 IL_0102: br.s IL_010a // sequence point: 10 IL_0104: ldc.i4.s 10 IL_0106: stloc.s V_9 IL_0108: br.s IL_010a // sequence point: <hidden> IL_010a: ldc.i4.1 IL_010b: brtrue.s IL_010e // sequence point: switch ... } IL_010d: nop // sequence point: F() switch ... IL_010e: ldloc.s V_9 IL_0110: stloc.3 IL_0111: br IL_0198 // sequence point: <hidden> IL_0116: newobj ""C.<>c__DisplayClass0_3..ctor()"" IL_011b: stloc.s V_16 IL_011d: call ""object C.F()"" IL_0122: stloc.s V_17 IL_0124: ldc.i4.1 IL_0125: brtrue.s IL_0128 // sequence point: switch ... IL_0127: nop // sequence point: <hidden> IL_0128: ldloc.s V_17 IL_012a: isinst ""C"" IL_012f: stloc.s V_18 IL_0131: ldloc.s V_18 IL_0133: brfalse.s IL_016f IL_0135: ldloc.s V_18 IL_0137: callvirt ""object C.P.get"" IL_013c: stloc.s V_19 // sequence point: <hidden> IL_013e: ldloc.s V_19 IL_0140: isinst ""int"" IL_0145: brfalse.s IL_016f IL_0147: ldloc.s V_16 IL_0149: ldloc.s V_19 IL_014b: unbox.any ""int"" IL_0150: stfld ""int C.<>c__DisplayClass0_3.<r>5__6"" // sequence point: <hidden> IL_0155: br.s IL_0157 // sequence point: <hidden> IL_0157: br.s IL_0159 // sequence point: G(() => r) IL_0159: ldloc.s V_16 IL_015b: ldftn ""int C.<>c__DisplayClass0_3.<M>b__3()"" IL_0161: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0166: call ""int C.G(System.Func<int>)"" IL_016b: stloc.s V_9 IL_016d: br.s IL_0175 // sequence point: 20 IL_016f: ldc.i4.s 20 IL_0171: stloc.s V_9 IL_0173: br.s IL_0175 // sequence point: <hidden> IL_0175: ldc.i4.1 IL_0176: brtrue.s IL_0179 // sequence point: F() switch ... IL_0178: nop // sequence point: F() switch ... IL_0179: ldloc.s V_9 IL_017b: stloc.3 IL_017c: br.s IL_0198 // sequence point: <hidden> IL_017e: br.s IL_0180 // sequence point: G(() => s) IL_0180: ldloc.2 IL_0181: ldftn ""int C.<>c__DisplayClass0_1.<M>b__1()"" IL_0187: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_018c: call ""int C.G(System.Func<int>)"" IL_0191: stloc.3 IL_0192: br.s IL_0198 // sequence point: 0 IL_0194: ldc.i4.0 IL_0195: stloc.3 IL_0196: br.s IL_0198 // sequence point: <hidden> IL_0198: ldc.i4.1 IL_0199: brtrue.s IL_019c // sequence point: return F() s ... }; IL_019b: nop // sequence point: <hidden> IL_019c: ldloc.0 IL_019d: ldloc.3 IL_019e: stfld ""int C.<>c__DisplayClass0_0.<t>5__2"" IL_01a3: ldc.i4.1 IL_01a4: brtrue.s IL_01a7 // sequence point: switch ... } IL_01a6: nop // sequence point: <hidden> IL_01a7: br.s IL_01a9 // sequence point: when t > 0 IL_01a9: ldloc.0 IL_01aa: ldfld ""int C.<>c__DisplayClass0_0.<t>5__2"" IL_01af: ldc.i4.0 IL_01b0: bgt.s IL_01b4 // sequence point: <hidden> IL_01b2: br.s IL_01c8 // sequence point: G(() => t) IL_01b4: ldloc.0 IL_01b5: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()"" IL_01bb: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_01c0: call ""int C.G(System.Func<int>)"" IL_01c5: stloc.1 IL_01c6: br.s IL_01cc // sequence point: 0 IL_01c8: ldc.i4.0 IL_01c9: stloc.1 IL_01ca: br.s IL_01cc // sequence point: <hidden> IL_01cc: ldc.i4.1 IL_01cd: brtrue.s IL_01d0 // sequence point: return F() s ... }; IL_01cf: nop // sequence point: <hidden> IL_01d0: ldloc.1 IL_01d1: stloc.s V_20 IL_01d3: br.s IL_01d5 // sequence point: } IL_01d5: ldloc.s V_20 IL_01d7: ret } "); verifier.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""30"" offset=""22"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""22"" /> <slot kind=""35"" offset=""22"" ordinal=""1"" /> <slot kind=""35"" offset=""22"" ordinal=""2"" /> <slot kind=""35"" offset=""22"" ordinal=""3"" /> <slot kind=""30"" offset=""63"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""63"" /> <slot kind=""35"" offset=""63"" ordinal=""1"" /> <slot kind=""35"" offset=""63"" ordinal=""2"" /> <slot kind=""35"" offset=""63"" ordinal=""3"" /> <slot kind=""35"" offset=""63"" ordinal=""4"" /> <slot kind=""35"" offset=""63"" ordinal=""5"" /> <slot kind=""30"" offset=""238"" /> <slot kind=""35"" offset=""238"" /> <slot kind=""35"" offset=""238"" ordinal=""1"" /> <slot kind=""35"" offset=""238"" ordinal=""2"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <closure offset=""22"" /> <closure offset=""63"" /> <closure offset=""238"" /> <lambda offset=""511"" closure=""0"" /> <lambda offset=""407"" closure=""1"" /> <lambda offset=""157"" closure=""2"" /> <lambda offset=""313"" closure=""3"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" hidden=""true"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> <entry offset=""0x57"" hidden=""true"" document=""1"" /> <entry offset=""0x70"" hidden=""true"" document=""1"" /> <entry offset=""0x75"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""9"" startColumn=""22"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x87"" hidden=""true"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0xb4"" hidden=""true"" document=""1"" /> <entry offset=""0xbd"" hidden=""true"" document=""1"" /> <entry offset=""0xd3"" hidden=""true"" document=""1"" /> <entry offset=""0xea"" hidden=""true"" document=""1"" /> <entry offset=""0xec"" hidden=""true"" document=""1"" /> <entry offset=""0xee"" startLine=""11"" startColumn=""59"" endLine=""11"" endColumn=""73"" document=""1"" /> <entry offset=""0x104"" startLine=""12"" startColumn=""27"" endLine=""12"" endColumn=""29"" document=""1"" /> <entry offset=""0x10a"" hidden=""true"" document=""1"" /> <entry offset=""0x10d"" startLine=""7"" startColumn=""20"" endLine=""21"" endColumn=""10"" document=""1"" /> <entry offset=""0x10e"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x116"" hidden=""true"" document=""1"" /> <entry offset=""0x127"" startLine=""14"" startColumn=""22"" endLine=""18"" endColumn=""19"" document=""1"" /> <entry offset=""0x128"" hidden=""true"" document=""1"" /> <entry offset=""0x13e"" hidden=""true"" document=""1"" /> <entry offset=""0x155"" hidden=""true"" document=""1"" /> <entry offset=""0x157"" hidden=""true"" document=""1"" /> <entry offset=""0x159"" startLine=""16"" startColumn=""40"" endLine=""16"" endColumn=""50"" document=""1"" /> <entry offset=""0x16f"" startLine=""17"" startColumn=""27"" endLine=""17"" endColumn=""29"" document=""1"" /> <entry offset=""0x175"" hidden=""true"" document=""1"" /> <entry offset=""0x178"" startLine=""9"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x179"" startLine=""14"" startColumn=""18"" endLine=""18"" endColumn=""19"" document=""1"" /> <entry offset=""0x17e"" hidden=""true"" document=""1"" /> <entry offset=""0x180"" startLine=""19"" startColumn=""31"" endLine=""19"" endColumn=""41"" document=""1"" /> <entry offset=""0x194"" startLine=""20"" startColumn=""18"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x198"" hidden=""true"" document=""1"" /> <entry offset=""0x19b"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" /> <entry offset=""0x19c"" hidden=""true"" document=""1"" /> <entry offset=""0x1a6"" startLine=""22"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x1a7"" hidden=""true"" document=""1"" /> <entry offset=""0x1a9"" startLine=""24"" startColumn=""19"" endLine=""24"" endColumn=""29"" document=""1"" /> <entry offset=""0x1b2"" hidden=""true"" document=""1"" /> <entry offset=""0x1b4"" startLine=""24"" startColumn=""33"" endLine=""24"" endColumn=""43"" document=""1"" /> <entry offset=""0x1c8"" startLine=""25"" startColumn=""18"" endLine=""25"" endColumn=""19"" document=""1"" /> <entry offset=""0x1cc"" hidden=""true"" document=""1"" /> <entry offset=""0x1cf"" startLine=""7"" startColumn=""9"" endLine=""26"" endColumn=""11"" document=""1"" /> <entry offset=""0x1d0"" hidden=""true"" document=""1"" /> <entry offset=""0x1d5"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1d8""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x1d5""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x1d5"" attributes=""0"" /> <scope startOffset=""0x7"" endOffset=""0x1a3""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""2"" il_start=""0x7"" il_end=""0x1a3"" attributes=""0"" /> <scope startOffset=""0x75"" endOffset=""0x111""> <local name=""CS$&lt;&gt;8__locals2"" il_index=""8"" il_start=""0x75"" il_end=""0x111"" attributes=""0"" /> </scope> <scope startOffset=""0x116"" endOffset=""0x17c""> <local name=""CS$&lt;&gt;8__locals3"" il_index=""16"" il_start=""0x116"" il_end=""0x17c"" attributes=""0"" /> </scope> </scope> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")] [ConditionalFact(typeof(CoreClrOnly))] public void NestedSwitchExpressions_Closures_01() { string source = WithWindowsLineBreaks( @"using System; class C { static int F(object o) { return o switch { int i => new Func<int>(() => i + i switch { 1 => 2, _ => 3 })(), _ => 4 }; } }"); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyTypeIL("C", @".class private auto ansi beforefieldinit C extends [netstandard]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<i>5__2' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a1 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance int32 '<F>b__0' () cil managed { // Method begins at RVA 0x20ac // Code size 38 (0x26) .maxstack 2 .locals init ( [0] int32, [1] int32 ) IL_0000: ldarg.0 IL_0001: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_0011: ldc.i4.1 IL_0012: beq.s IL_0016 IL_0014: br.s IL_001a IL_0016: ldc.i4.2 IL_0017: stloc.1 IL_0018: br.s IL_001e IL_001a: ldc.i4.3 IL_001b: stloc.1 IL_001c: br.s IL_001e IL_001e: ldc.i4.1 IL_001f: brtrue.s IL_0022 IL_0021: nop IL_0022: ldloc.0 IL_0023: ldloc.1 IL_0024: add IL_0025: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__0' } // end of class <>c__DisplayClass0_0 // Methods .method private hidebysig static int32 F ( object o ) cil managed { // Method begins at RVA 0x2050 // Code size 69 (0x45) .maxstack 2 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] int32, [2] int32 ) IL_0000: nop IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: isinst [netstandard]System.Int32 IL_0011: brfalse.s IL_0037 IL_0013: ldloc.0 IL_0014: ldarg.0 IL_0015: unbox.any [netstandard]System.Int32 IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_001f: br.s IL_0021 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ldftn instance int32 C/'<>c__DisplayClass0_0'::'<F>b__0'() IL_002a: newobj instance void class [netstandard]System.Func`1<int32>::.ctor(object, native int) IL_002f: callvirt instance !0 class [netstandard]System.Func`1<int32>::Invoke() IL_0034: stloc.1 IL_0035: br.s IL_003b IL_0037: ldc.i4.4 IL_0038: stloc.1 IL_0039: br.s IL_003b IL_003b: ldc.i4.1 IL_003c: brtrue.s IL_003f IL_003e: nop IL_003f: ldloc.1 IL_0040: stloc.2 IL_0041: br.s IL_0043 IL_0043: ldloc.2 IL_0044: ret } // end of method C::F .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a1 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C::.ctor } // end of class C "); verifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""80"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" /> <entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""19"" document=""1"" /> <entry offset=""0x3b"" hidden=""true"" document=""1"" /> <entry offset=""0x3e"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x45""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x43""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x43"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> <encLocalSlotMap> <slot kind=""28"" offset=""86"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0xa"" startLine=""8"" startColumn=""48"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x1a"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""23"" document=""1"" /> <entry offset=""0x1e"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""42"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(50321, "https://github.com/dotnet/roslyn/issues/50321")] [ConditionalFact(typeof(CoreClrOnly))] public void NestedSwitchExpressions_Closures_02() { string source = WithWindowsLineBreaks( @"using System; class C { static string F(object o) { return o switch { int i => new Func<string>(() => ""1"" + i switch { 1 => new Func<string>(() => ""2"" + i)(), _ => ""3"" })(), _ => ""4"" }; } }"); var verifier = CompileAndVerify(source, options: TestOptions.DebugDll); verifier.VerifyTypeIL("C", @".class private auto ansi beforefieldinit C extends [netstandard]System.Object { // Nested Types .class nested private auto ansi sealed beforefieldinit '<>c__DisplayClass0_0' extends [netstandard]System.Object { .custom instance void [netstandard]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Fields .field public int32 '<i>5__2' .field public class [netstandard]System.Func`1<string> '<>9__1' // Methods .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a5 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method '<>c__DisplayClass0_0'::.ctor .method assembly hidebysig instance string '<F>b__0' () cil managed { // Method begins at RVA 0x20b0 // Code size 78 (0x4e) .maxstack 3 .locals init ( [0] string, [1] class [netstandard]System.Func`1<string> ) IL_0000: ldc.i4.1 IL_0001: brtrue.s IL_0004 IL_0003: nop IL_0004: ldarg.0 IL_0005: ldfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_000a: ldc.i4.1 IL_000b: beq.s IL_000f IL_000d: br.s IL_0036 IL_000f: ldarg.0 IL_0010: ldfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1' IL_0015: dup IL_0016: brtrue.s IL_002e IL_0018: pop IL_0019: ldarg.0 IL_001a: ldarg.0 IL_001b: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__1'() IL_0021: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int) IL_0026: dup IL_0027: stloc.1 IL_0028: stfld class [netstandard]System.Func`1<string> C/'<>c__DisplayClass0_0'::'<>9__1' IL_002d: ldloc.1 IL_002e: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke() IL_0033: stloc.0 IL_0034: br.s IL_003e IL_0036: ldstr ""3"" IL_003b: stloc.0 IL_003c: br.s IL_003e IL_003e: ldc.i4.1 IL_003f: brtrue.s IL_0042 IL_0041: nop IL_0042: ldstr ""1"" IL_0047: ldloc.0 IL_0048: call string [netstandard]System.String::Concat(string, string) IL_004d: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__0' .method assembly hidebysig instance string '<F>b__1' () cil managed { // Method begins at RVA 0x210a // Code size 22 (0x16) .maxstack 8 IL_0000: ldstr ""2"" IL_0005: ldarg.0 IL_0006: ldflda int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_000b: call instance string [netstandard]System.Int32::ToString() IL_0010: call string [netstandard]System.String::Concat(string, string) IL_0015: ret } // end of method '<>c__DisplayClass0_0'::'<F>b__1' } // end of class <>c__DisplayClass0_0 // Methods .method private hidebysig static string F ( object o ) cil managed { // Method begins at RVA 0x2050 // Code size 73 (0x49) .maxstack 2 .locals init ( [0] class C/'<>c__DisplayClass0_0', [1] string, [2] string ) IL_0000: nop IL_0001: newobj instance void C/'<>c__DisplayClass0_0'::.ctor() IL_0006: stloc.0 IL_0007: ldc.i4.1 IL_0008: brtrue.s IL_000b IL_000a: nop IL_000b: ldarg.0 IL_000c: isinst [netstandard]System.Int32 IL_0011: brfalse.s IL_0037 IL_0013: ldloc.0 IL_0014: ldarg.0 IL_0015: unbox.any [netstandard]System.Int32 IL_001a: stfld int32 C/'<>c__DisplayClass0_0'::'<i>5__2' IL_001f: br.s IL_0021 IL_0021: br.s IL_0023 IL_0023: ldloc.0 IL_0024: ldftn instance string C/'<>c__DisplayClass0_0'::'<F>b__0'() IL_002a: newobj instance void class [netstandard]System.Func`1<string>::.ctor(object, native int) IL_002f: callvirt instance !0 class [netstandard]System.Func`1<string>::Invoke() IL_0034: stloc.1 IL_0035: br.s IL_003f IL_0037: ldstr ""4"" IL_003c: stloc.1 IL_003d: br.s IL_003f IL_003f: ldc.i4.1 IL_0040: brtrue.s IL_0043 IL_0042: nop IL_0043: ldloc.1 IL_0044: stloc.2 IL_0045: br.s IL_0047 IL_0047: ldloc.2 IL_0048: ret } // end of method C::F .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { // Method begins at RVA 0x20a5 // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [netstandard]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C::.ctor } // end of class C "); verifier.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""11"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""11"" /> <lambda offset=""83"" closure=""0"" /> <lambda offset=""158"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" hidden=""true"" document=""1"" /> <entry offset=""0xa"" startLine=""6"" startColumn=""18"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x23"" startLine=""8"" startColumn=""22"" endLine=""12"" endColumn=""17"" document=""1"" /> <entry offset=""0x37"" startLine=""13"" startColumn=""18"" endLine=""13"" endColumn=""21"" document=""1"" /> <entry offset=""0x3f"" hidden=""true"" document=""1"" /> <entry offset=""0x42"" startLine=""6"" startColumn=""9"" endLine=""14"" endColumn=""11"" document=""1"" /> <entry offset=""0x43"" hidden=""true"" document=""1"" /> <entry offset=""0x47"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x49""> <namespace name=""System"" /> <scope startOffset=""0x1"" endOffset=""0x47""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x47"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x3"" startLine=""8"" startColumn=""53"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x4"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" startLine=""10"" startColumn=""22"" endLine=""10"" endColumn=""55"" document=""1"" /> <entry offset=""0x36"" startLine=""11"" startColumn=""22"" endLine=""11"" endColumn=""25"" document=""1"" /> <entry offset=""0x3e"" hidden=""true"" document=""1"" /> <entry offset=""0x41"" startLine=""8"" startColumn=""45"" endLine=""12"" endColumn=""14"" document=""1"" /> <entry offset=""0x42"" hidden=""true"" document=""1"" /> </sequencePoints> </method> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;F&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName=""F"" parameterNames=""o"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""45"" endLine=""10"" endColumn=""52"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SwitchExpression_MethodBody() { string source = @" using System; public class C { static int M() => F() switch { 1 => 1, C { P: int p, Q: C { P: int q } } => G(() => p + q), _ => 0 }; object P { get; set; } object Q { get; set; } static object F() => null; static int G(Func<int> f) => 0; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 171 (0xab) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0, //CS$<>8__locals0 int V_1, object V_2, int V_3, C V_4, object V_5, object V_6, C V_7, object V_8) // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: call ""object C.F()"" IL_000b: stloc.2 IL_000c: ldc.i4.1 IL_000d: brtrue.s IL_0010 // sequence point: switch ... } IL_000f: nop // sequence point: <hidden> IL_0010: ldloc.2 IL_0011: isinst ""int"" IL_0016: brfalse.s IL_0025 IL_0018: ldloc.2 IL_0019: unbox.any ""int"" IL_001e: stloc.3 // sequence point: <hidden> IL_001f: ldloc.3 IL_0020: ldc.i4.1 IL_0021: beq.s IL_0087 IL_0023: br.s IL_00a1 IL_0025: ldloc.2 IL_0026: isinst ""C"" IL_002b: stloc.s V_4 IL_002d: ldloc.s V_4 IL_002f: brfalse.s IL_00a1 IL_0031: ldloc.s V_4 IL_0033: callvirt ""object C.P.get"" IL_0038: stloc.s V_5 // sequence point: <hidden> IL_003a: ldloc.s V_5 IL_003c: isinst ""int"" IL_0041: brfalse.s IL_00a1 IL_0043: ldloc.0 IL_0044: ldloc.s V_5 IL_0046: unbox.any ""int"" IL_004b: stfld ""int C.<>c__DisplayClass0_0.<p>5__2"" // sequence point: <hidden> IL_0050: ldloc.s V_4 IL_0052: callvirt ""object C.Q.get"" IL_0057: stloc.s V_6 // sequence point: <hidden> IL_0059: ldloc.s V_6 IL_005b: isinst ""C"" IL_0060: stloc.s V_7 IL_0062: ldloc.s V_7 IL_0064: brfalse.s IL_00a1 IL_0066: ldloc.s V_7 IL_0068: callvirt ""object C.P.get"" IL_006d: stloc.s V_8 // sequence point: <hidden> IL_006f: ldloc.s V_8 IL_0071: isinst ""int"" IL_0076: brfalse.s IL_00a1 IL_0078: ldloc.0 IL_0079: ldloc.s V_8 IL_007b: unbox.any ""int"" IL_0080: stfld ""int C.<>c__DisplayClass0_0.<q>5__3"" // sequence point: <hidden> IL_0085: br.s IL_008b // sequence point: 1 IL_0087: ldc.i4.1 IL_0088: stloc.1 IL_0089: br.s IL_00a5 // sequence point: <hidden> IL_008b: br.s IL_008d // sequence point: G(() => p + q) IL_008d: ldloc.0 IL_008e: ldftn ""int C.<>c__DisplayClass0_0.<M>b__0()"" IL_0094: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0099: call ""int C.G(System.Func<int>)"" IL_009e: stloc.1 IL_009f: br.s IL_00a5 // sequence point: 0 IL_00a1: ldc.i4.0 IL_00a2: stloc.1 IL_00a3: br.s IL_00a5 // sequence point: <hidden> IL_00a5: ldc.i4.1 IL_00a6: brtrue.s IL_00a9 // sequence point: F() switch ... } IL_00a8: nop // sequence point: <hidden> IL_00a9: ldloc.1 IL_00aa: ret } "); verifier.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""7"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""7"" /> <slot kind=""35"" offset=""7"" ordinal=""1"" /> <slot kind=""35"" offset=""7"" ordinal=""2"" /> <slot kind=""35"" offset=""7"" ordinal=""3"" /> <slot kind=""35"" offset=""7"" ordinal=""4"" /> <slot kind=""35"" offset=""7"" ordinal=""5"" /> <slot kind=""35"" offset=""7"" ordinal=""6"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""7"" /> <lambda offset=""92"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""27"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0x10"" hidden=""true"" document=""1"" /> <entry offset=""0x1f"" hidden=""true"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x50"" hidden=""true"" document=""1"" /> <entry offset=""0x59"" hidden=""true"" document=""1"" /> <entry offset=""0x6f"" hidden=""true"" document=""1"" /> <entry offset=""0x85"" hidden=""true"" document=""1"" /> <entry offset=""0x87"" startLine=""7"" startColumn=""14"" endLine=""7"" endColumn=""15"" document=""1"" /> <entry offset=""0x8b"" hidden=""true"" document=""1"" /> <entry offset=""0x8d"" startLine=""8"" startColumn=""46"" endLine=""8"" endColumn=""60"" document=""1"" /> <entry offset=""0xa1"" startLine=""9"" startColumn=""14"" endLine=""9"" endColumn=""15"" document=""1"" /> <entry offset=""0xa5"" hidden=""true"" document=""1"" /> <entry offset=""0xa8"" startLine=""5"" startColumn=""23"" endLine=""10"" endColumn=""6"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xab""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0xab"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(37261, "https://github.com/dotnet/roslyn/issues/37261")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SwitchExpression_MethodBody_02() { string source = @" using System; public class C { static Action M1(int x) => () => { _ = x; }; static Action M2(int x) => x switch { _ => () => { _ = x; } }; } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M1", sequencePoints: "C.M1", source: source, expectedIL: @" { // Code size 26 (0x1a) .maxstack 2 .locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""int C.<>c__DisplayClass0_0.x"" // sequence point: () => { _ = x; } IL_000d: ldloc.0 IL_000e: ldftn ""void C.<>c__DisplayClass0_0.<M1>b__0()"" IL_0014: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0019: ret } "); verifier.VerifyIL("C.M2", sequencePoints: "C.M2", source: source, expectedIL: @" { // Code size 40 (0x28) .maxstack 2 .locals init (C.<>c__DisplayClass1_0 V_0, //CS$<>8__locals0 System.Action V_1) // sequence point: <hidden> IL_0000: newobj ""C.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldarg.0 IL_0008: stfld ""int C.<>c__DisplayClass1_0.x"" // sequence point: x switch { _ => () => { _ = x; } } IL_000d: ldc.i4.1 IL_000e: brtrue.s IL_0011 // sequence point: switch { _ => () => { _ = x; } } IL_0010: nop // sequence point: <hidden> IL_0011: br.s IL_0013 // sequence point: () => { _ = x; } IL_0013: ldloc.0 IL_0014: ldftn ""void C.<>c__DisplayClass1_0.<M2>b__0()"" IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_001f: stloc.1 IL_0020: br.s IL_0022 // sequence point: <hidden> IL_0022: ldc.i4.1 IL_0023: brtrue.s IL_0026 // sequence point: x switch { _ => () => { _ = x; } } IL_0025: nop // sequence point: <hidden> IL_0026: ldloc.1 IL_0027: ret } "); verifier.VerifyPdb("C.M1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M1"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""0"" /> <lambda offset=""9"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""32"" endLine=""5"" endColumn=""48"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); verifier.VerifyPdb("C.M2", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M2"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""C"" methodName=""M1"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>1</methodOrdinal> <closure offset=""0"" /> <lambda offset=""25"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0xd"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""34"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x13"" startLine=""6"" startColumn=""48"" endLine=""6"" endColumn=""64"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""6"" startColumn=""32"" endLine=""6"" endColumn=""66"" document=""1"" /> <entry offset=""0x26"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void SyntaxOffset_OutVarInInitializers_SwitchExpression() { var source = @"class C { static int G(out int x) => throw null; static int F(System.Func<int> x) => throw null; C() { } int y1 = G(out var z) switch { _ => F(() => z) }; // line 7 } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-26"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""-26"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-26"" /> <lambda offset=""-4"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" /> <entry offset=""0x15"" startLine=""7"" startColumn=""27"" endLine=""7"" endColumn=""53"" document=""1"" /> <entry offset=""0x16"" hidden=""true"" document=""1"" /> <entry offset=""0x18"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""51"" document=""1"" /> <entry offset=""0x2c"" hidden=""true"" document=""1"" /> <entry offset=""0x2f"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""54"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""8"" document=""1"" /> <entry offset=""0x3e"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""10"" document=""1"" /> <entry offset=""0x3f"" startLine=""5"" startColumn=""11"" endLine=""5"" endColumn=""12"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x40""> <scope startOffset=""0x0"" endOffset=""0x37""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x37"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [WorkItem(43468, "https://github.com/dotnet/roslyn/issues/43468")] [Fact] public void HiddenSequencePointAtSwitchExpressionFinalMergePoint() { var source = @"class C { static int M(int x) { var y = x switch { 1 => 2, _ => 3, }; return y; } } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(c); verifier.VerifyIL("C.M", sequencePoints: "C.M", source: source, expectedIL: @" { // Code size 31 (0x1f) .maxstack 2 .locals init (int V_0, //y int V_1, int V_2) // sequence point: { IL_0000: nop // sequence point: var y = x sw ... }; IL_0001: ldc.i4.1 IL_0002: brtrue.s IL_0005 // sequence point: switch ... } IL_0004: nop // sequence point: <hidden> IL_0005: ldarg.0 IL_0006: ldc.i4.1 IL_0007: beq.s IL_000b IL_0009: br.s IL_000f // sequence point: 2 IL_000b: ldc.i4.2 IL_000c: stloc.1 IL_000d: br.s IL_0013 // sequence point: 3 IL_000f: ldc.i4.3 IL_0010: stloc.1 IL_0011: br.s IL_0013 // sequence point: <hidden> IL_0013: ldc.i4.1 IL_0014: brtrue.s IL_0017 // sequence point: var y = x sw ... }; IL_0016: nop // sequence point: <hidden> IL_0017: ldloc.1 IL_0018: stloc.0 // sequence point: return y; IL_0019: ldloc.0 IL_001a: stloc.2 IL_001b: br.s IL_001d // sequence point: } IL_001d: ldloc.2 IL_001e: ret } "); } [WorkItem(12378, "https://github.com/dotnet/roslyn/issues/12378")] [WorkItem(13971, "https://github.com/dotnet/roslyn/issues/13971")] [Fact] public void Patterns_SwitchStatement_Constant() { string source = WithWindowsLineBreaks( @"class Program { static void M(object o) { switch (o) { case 1 when o == null: case 4: case 2 when o == null: break; case 1 when o != null: case 5: case 3 when o != null: break; default: break; case 1: break; } switch (o) { case 1: break; default: break; } switch (o) { default: break; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); CompileAndVerify(c).VerifyIL(qualifiedMethodName: "Program.M", sequencePoints: "Program.M", source: source, expectedIL: @"{ // Code size 123 (0x7b) .maxstack 2 .locals init (object V_0, int V_1, object V_2, object V_3, int V_4, object V_5, object V_6, object V_7) // sequence point: { IL_0000: nop // sequence point: switch (o) IL_0001: ldarg.0 IL_0002: stloc.2 // sequence point: <hidden> IL_0003: ldloc.2 IL_0004: stloc.0 // sequence point: <hidden> IL_0005: ldloc.0 IL_0006: isinst ""int"" IL_000b: brfalse.s IL_004a IL_000d: ldloc.0 IL_000e: unbox.any ""int"" IL_0013: stloc.1 // sequence point: <hidden> IL_0014: ldloc.1 IL_0015: ldc.i4.1 IL_0016: sub IL_0017: switch ( IL_0032, IL_0037, IL_0043, IL_003c, IL_0048) IL_0030: br.s IL_004a // sequence point: when o == null IL_0032: ldarg.0 IL_0033: brfalse.s IL_003c // sequence point: <hidden> IL_0035: br.s IL_003e // sequence point: when o == null IL_0037: ldarg.0 IL_0038: brfalse.s IL_003c // sequence point: <hidden> IL_003a: br.s IL_004a // sequence point: break; IL_003c: br.s IL_004e // sequence point: when o != null IL_003e: ldarg.0 IL_003f: brtrue.s IL_0048 // sequence point: <hidden> IL_0041: br.s IL_004c // sequence point: when o != null IL_0043: ldarg.0 IL_0044: brtrue.s IL_0048 // sequence point: <hidden> IL_0046: br.s IL_004a // sequence point: break; IL_0048: br.s IL_004e // sequence point: break; IL_004a: br.s IL_004e // sequence point: break; IL_004c: br.s IL_004e // sequence point: switch (o) IL_004e: ldarg.0 IL_004f: stloc.s V_5 // sequence point: <hidden> IL_0051: ldloc.s V_5 IL_0053: stloc.3 // sequence point: <hidden> IL_0054: ldloc.3 IL_0055: isinst ""int"" IL_005a: brfalse.s IL_006d IL_005c: ldloc.3 IL_005d: unbox.any ""int"" IL_0062: stloc.s V_4 // sequence point: <hidden> IL_0064: ldloc.s V_4 IL_0066: ldc.i4.1 IL_0067: beq.s IL_006b IL_0069: br.s IL_006d // sequence point: break; IL_006b: br.s IL_006f // sequence point: break; IL_006d: br.s IL_006f // sequence point: switch (o) IL_006f: ldarg.0 IL_0070: stloc.s V_7 // sequence point: <hidden> IL_0072: ldloc.s V_7 IL_0074: stloc.s V_6 // sequence point: <hidden> IL_0076: br.s IL_0078 // sequence point: break; IL_0078: br.s IL_007a // sequence point: } IL_007a: ret }"); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""35"" offset=""378"" /> <slot kind=""35"" offset=""378"" ordinal=""1"" /> <slot kind=""1"" offset=""378"" /> <slot kind=""35"" offset=""511"" /> <slot kind=""1"" offset=""511"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""19"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" hidden=""true"" document=""1"" /> <entry offset=""0x32"" startLine=""7"" startColumn=""20"" endLine=""7"" endColumn=""34"" document=""1"" /> <entry offset=""0x35"" hidden=""true"" document=""1"" /> <entry offset=""0x37"" startLine=""9"" startColumn=""20"" endLine=""9"" endColumn=""34"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""23"" document=""1"" /> <entry offset=""0x3e"" startLine=""11"" startColumn=""20"" endLine=""11"" endColumn=""34"" document=""1"" /> <entry offset=""0x41"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""13"" startColumn=""20"" endLine=""13"" endColumn=""34"" document=""1"" /> <entry offset=""0x46"" hidden=""true"" document=""1"" /> <entry offset=""0x48"" startLine=""14"" startColumn=""17"" endLine=""14"" endColumn=""23"" document=""1"" /> <entry offset=""0x4a"" startLine=""16"" startColumn=""17"" endLine=""16"" endColumn=""23"" document=""1"" /> <entry offset=""0x4c"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""23"" document=""1"" /> <entry offset=""0x4e"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""19"" document=""1"" /> <entry offset=""0x51"" hidden=""true"" document=""1"" /> <entry offset=""0x54"" hidden=""true"" document=""1"" /> <entry offset=""0x64"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x6d"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""1"" /> <entry offset=""0x6f"" startLine=""27"" startColumn=""9"" endLine=""27"" endColumn=""19"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x76"" hidden=""true"" document=""1"" /> <entry offset=""0x78"" startLine=""30"" startColumn=""17"" endLine=""30"" endColumn=""23"" document=""1"" /> <entry offset=""0x7a"" startLine=""32"" startColumn=""5"" endLine=""32"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [Fact] public void Patterns_SwitchStatement_Tuple() { string source = WithWindowsLineBreaks(@" public class C { static int F(int i) { switch (G()) { case (1, 2): return 3; default: return 0; }; } static (object, object) G() => (2, 3); }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); var cv = CompileAndVerify(c); cv.VerifyIL("C.F", @" { // Code size 80 (0x50) .maxstack 2 .locals init (System.ValueTuple<object, object> V_0, object V_1, int V_2, object V_3, int V_4, System.ValueTuple<object, object> V_5, int V_6) IL_0000: nop IL_0001: call ""System.ValueTuple<object, object> C.G()"" IL_0006: stloc.s V_5 IL_0008: ldloc.s V_5 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldfld ""object System.ValueTuple<object, object>.Item1"" IL_0011: stloc.1 IL_0012: ldloc.1 IL_0013: isinst ""int"" IL_0018: brfalse.s IL_0048 IL_001a: ldloc.1 IL_001b: unbox.any ""int"" IL_0020: stloc.2 IL_0021: ldloc.2 IL_0022: ldc.i4.1 IL_0023: bne.un.s IL_0048 IL_0025: ldloc.0 IL_0026: ldfld ""object System.ValueTuple<object, object>.Item2"" IL_002b: stloc.3 IL_002c: ldloc.3 IL_002d: isinst ""int"" IL_0032: brfalse.s IL_0048 IL_0034: ldloc.3 IL_0035: unbox.any ""int"" IL_003a: stloc.s V_4 IL_003c: ldloc.s V_4 IL_003e: ldc.i4.2 IL_003f: beq.s IL_0043 IL_0041: br.s IL_0048 IL_0043: ldc.i4.3 IL_0044: stloc.s V_6 IL_0046: br.s IL_004d IL_0048: ldc.i4.0 IL_0049: stloc.s V_6 IL_004b: br.s IL_004d IL_004d: ldloc.s V_6 IL_004f: ret } "); c.VerifyPdb("C.F", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""35"" offset=""11"" /> <slot kind=""35"" offset=""11"" ordinal=""1"" /> <slot kind=""35"" offset=""11"" ordinal=""2"" /> <slot kind=""35"" offset=""11"" ordinal=""3"" /> <slot kind=""35"" offset=""11"" ordinal=""4"" /> <slot kind=""1"" offset=""11"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""21"" document=""1"" /> <entry offset=""0x8"" hidden=""true"" document=""1"" /> <entry offset=""0xb"" hidden=""true"" document=""1"" /> <entry offset=""0x12"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" hidden=""true"" document=""1"" /> <entry offset=""0x2c"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" hidden=""true"" document=""1"" /> <entry offset=""0x43"" startLine=""8"" startColumn=""26"" endLine=""8"" endColumn=""35"" document=""1"" /> <entry offset=""0x48"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""31"" document=""1"" /> <entry offset=""0x4d"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } #endregion #region Tuples [Fact] public void SyntaxOffset_TupleDeconstruction() { var source = @"class C { int F() { (int a, (_, int c)) = (1, (2, 3)); return a + c; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""7"" /> <slot kind=""0"" offset=""18"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" /> <entry offset=""0x5"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""69"" document=""1"" /> <entry offset=""0xb"" startLine=""1"" startColumn=""70"" endLine=""1"" endColumn=""71"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> <local name=""c"" il_index=""1"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void TestDeconstruction() { var source = @" public class C { public static (int, int) F() => (1, 2); public static void Main() { int x, y; (x, y) = F(); System.Console.WriteLine(x + y); } } "; var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.Main", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0, //x int V_1) //y // sequence point: { IL_0000: nop // sequence point: (x, y) = F(); IL_0001: call ""System.ValueTuple<int, int> C.F()"" IL_0006: dup IL_0007: ldfld ""int System.ValueTuple<int, int>.Item1"" IL_000c: stloc.0 IL_000d: ldfld ""int System.ValueTuple<int, int>.Item2"" IL_0012: stloc.1 // sequence point: System.Console.WriteLine(x + y); IL_0013: ldloc.0 IL_0014: ldloc.1 IL_0015: add IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: nop // sequence point: } IL_001c: ret } ", sequencePoints: "C.Main", source: source); } [Fact] public void SyntaxOffset_TupleParenthesized() { var source = @"class C { int F() { (int, (int, int)) x = (1, (2, 3)); return x.Item1 + x.Item2.Item1 + x.Item2.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""20"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""55"" document=""1"" /> <entry offset=""0x10"" startLine=""1"" startColumn=""56"" endLine=""1"" endColumn=""103"" document=""1"" /> <entry offset=""0x31"" startLine=""1"" startColumn=""104"" endLine=""1"" endColumn=""105"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x33""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x33"" attributes=""0"" /> </scope> </method> </methods> </symbols>" ); } [Fact] public void SyntaxOffset_TupleVarDefined() { var source = @"class C { int F() { var x = (1, 2); return x.Item1 + x.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""6"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""36"" document=""1"" /> <entry offset=""0xa"" startLine=""1"" startColumn=""37"" endLine=""1"" endColumn=""62"" document=""1"" /> <entry offset=""0x1a"" startLine=""1"" startColumn=""63"" endLine=""1"" endColumn=""64"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1c""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void SyntaxOffset_TupleIgnoreDeconstructionIfVariableDeclared() { var source = @"class C { int F() { (int x, int y) a = (1, 2); return a.Item1 + a.Item2; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, references: s_valueTupleRefs); c.VerifyPdb("C.F", @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <tupleElementNames> <local elementNames=""|x|y"" slotIndex=""0"" localName=""a"" scopeStart=""0x0"" scopeEnd=""0x0"" /> </tupleElementNames> <encLocalSlotMap> <slot kind=""0"" offset=""17"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""19"" endLine=""1"" endColumn=""20"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""21"" endLine=""1"" endColumn=""47"" document=""1"" /> <entry offset=""0x9"" startLine=""1"" startColumn=""48"" endLine=""1"" endColumn=""73"" document=""1"" /> <entry offset=""0x19"" startLine=""1"" startColumn=""74"" endLine=""1"" endColumn=""75"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""a"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } #endregion #region OutVar [Fact] public void SyntaxOffset_OutVarInConstructor() { var source = @" class B { B(out int z) { z = 2; } } class C { int F = G(out var v1); int P => G(out var v2); C() : base(out var v3) { G(out var v4); } int G(out int x) { x = 1; return 2; } } "; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyDiagnostics( // (9,13): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.G(out int)' // int F = G(out var v1); Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "G").WithArguments("C.G(out int)").WithLocation(9, 13), // (13,7): error CS1729: 'object' does not contain a constructor that takes 1 arguments // : base(out var v3) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(13, 7)); } [Fact] public void SyntaxOffset_OutVarInMethod() { var source = @"class C { int G(out int x) { int z = 1; G(out var y); G(out var w); return x = y; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G"" parameterNames=""x""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""6"" /> <slot kind=""0"" offset=""23"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""temp"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""28"" endLine=""1"" endColumn=""29"" document=""1"" /> <entry offset=""0x1"" startLine=""1"" startColumn=""30"" endLine=""1"" endColumn=""40"" document=""1"" /> <entry offset=""0x3"" startLine=""1"" startColumn=""41"" endLine=""1"" endColumn=""54"" document=""1"" /> <entry offset=""0xc"" startLine=""1"" startColumn=""55"" endLine=""1"" endColumn=""68"" document=""1"" /> <entry offset=""0x15"" startLine=""1"" startColumn=""69"" endLine=""1"" endColumn=""82"" document=""1"" /> <entry offset=""0x1f"" startLine=""1"" startColumn=""83"" endLine=""1"" endColumn=""84"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""z"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> <local name=""y"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> <local name=""w"" il_index=""2"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_01() { var source = WithWindowsLineBreaks( @" class C : A { int x = G(out var x); int y {get;} = G(out var y); C() : base(G(out var z)) { } static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-36"" /> <slot kind=""0"" offset=""-22"" /> <slot kind=""0"" offset=""-3"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""26"" document=""1"" /> <entry offset=""0xd"" startLine=""5"" startColumn=""20"" endLine=""5"" endColumn=""32"" document=""1"" /> <entry offset=""0x1a"" startLine=""7"" startColumn=""11"" endLine=""7"" endColumn=""29"" document=""1"" /> <entry offset=""0x28"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x29"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> <scope startOffset=""0xd"" endOffset=""0x1a""> <local name=""y"" il_index=""1"" il_start=""0xd"" il_end=""0x1a"" attributes=""0"" /> </scope> <scope startOffset=""0x1a"" endOffset=""0x2a""> <local name=""z"" il_index=""2"" il_start=""0x1a"" il_end=""0x2a"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_02() { var source = WithWindowsLineBreaks( @" class C : A { C() : base(G(out var x)) { int y = 1; y++; } static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-3"" /> <slot kind=""0"" offset=""16"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0xf"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""19"" document=""1"" /> <entry offset=""0x11"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""13"" document=""1"" /> <entry offset=""0x15"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x16""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x16"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x16""> <local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x16"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_03() { var source = WithWindowsLineBreaks( @" class C : A { C() : base(G(out var x)) => G(out var y); static int G(out int x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""-3"" /> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""11"" endLine=""4"" endColumn=""29"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""8"" endLine=""5"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x17""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x17"" attributes=""0"" /> <scope startOffset=""0xe"" endOffset=""0x17""> <local name=""y"" il_index=""1"" il_start=""0xe"" il_end=""0x17"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_04() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } C() { } #line 2000 int y1 = G(out var z) + F(() => z); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <closure offset=""-25"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""40"" document=""1"" /> <entry offset=""0x29"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""8"" document=""1"" /> <entry offset=""0x30"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x31"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x32""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass2_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass2_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_05() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } #line 2000 int y1 { get; } = G(out var z) + F(() => z); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>5</methodOrdinal> <closure offset=""-25"" /> <lambda offset=""-2"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""23"" endLine=""2000"" endColumn=""48"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x31""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass5_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass5_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""46"" endLine=""2000"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_06() { var source = WithWindowsLineBreaks( @" class C { static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } #line 2000 int y1 = G(out var z) + F(() => z), y2 = G(out var u) + F(() => u); } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C..ctor", sequencePoints: "C..ctor", expectedIL: @" { // Code size 90 (0x5a) .maxstack 4 .locals init (C.<>c__DisplayClass4_0 V_0, //CS$<>8__locals0 C.<>c__DisplayClass4_1 V_1) //CS$<>8__locals1 ~IL_0000: newobj ""C.<>c__DisplayClass4_0..ctor()"" IL_0005: stloc.0 -IL_0006: ldarg.0 IL_0007: ldloc.0 IL_0008: ldflda ""int C.<>c__DisplayClass4_0.z"" IL_000d: call ""int C.G(out int)"" IL_0012: ldloc.0 IL_0013: ldftn ""int C.<>c__DisplayClass4_0.<.ctor>b__0()"" IL_0019: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_001e: call ""int C.F(System.Func<int>)"" IL_0023: add IL_0024: stfld ""int C.y1"" ~IL_0029: newobj ""C.<>c__DisplayClass4_1..ctor()"" IL_002e: stloc.1 -IL_002f: ldarg.0 IL_0030: ldloc.1 IL_0031: ldflda ""int C.<>c__DisplayClass4_1.u"" IL_0036: call ""int C.G(out int)"" IL_003b: ldloc.1 IL_003c: ldftn ""int C.<>c__DisplayClass4_1.<.ctor>b__1()"" IL_0042: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0047: call ""int C.F(System.Func<int>)"" IL_004c: add IL_004d: stfld ""int C.y2"" IL_0052: ldarg.0 IL_0053: call ""object..ctor()"" IL_0058: nop IL_0059: ret } "); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> <encLocalSlotMap> <slot kind=""30"" offset=""-52"" /> <slot kind=""30"" offset=""-25"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>4</methodOrdinal> <closure offset=""-52"" /> <closure offset=""-25"" /> <lambda offset=""-29"" closure=""0"" /> <lambda offset=""-2"" closure=""1"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""39"" document=""1"" /> <entry offset=""0x29"" hidden=""true"" document=""1"" /> <entry offset=""0x2f"" startLine=""2000"" startColumn=""41"" endLine=""2000"" endColumn=""71"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x5a""> <scope startOffset=""0x0"" endOffset=""0x29""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" /> </scope> <scope startOffset=""0x29"" endOffset=""0x52""> <local name=""CS$&lt;&gt;8__locals1"" il_index=""1"" il_start=""0x29"" il_end=""0x52"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass4_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass4_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""37"" endLine=""2000"" endColumn=""38"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass4_1.<.ctor>b__1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass4_1"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName=""G"" parameterNames=""x"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""69"" endLine=""2000"" endColumn=""70"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInInitializers_07() { var source = WithWindowsLineBreaks( @" class C : A { #line 2000 C() : base(G(out var z)+ F(() => z)) { } static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } } class A { public A(int x) {} } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""30"" offset=""-1"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""-1"" /> <lambda offset=""-3"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2000"" startColumn=""11"" endLine=""2000"" endColumn=""41"" document=""1"" /> <entry offset=""0x2a"" startLine=""2001"" startColumn=""5"" endLine=""2001"" endColumn=""6"" document=""1"" /> <entry offset=""0x2b"" startLine=""2002"" startColumn=""5"" endLine=""2002"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2c""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x2c"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__0""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2000"" startColumn=""38"" endLine=""2000"" endColumn=""39"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInQuery_01() { var source = WithWindowsLineBreaks( @" using System.Linq; class C { C() { var q = from a in new [] {1} where G(out var x1) > a select a; } static int G(out int x) { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""88"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""26"" document=""1"" /> <entry offset=""0x37"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x38""> <namespace name=""System.Linq"" /> <scope startOffset=""0x7"" endOffset=""0x38""> <local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c.<.ctor>b__0_0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""0"" offset=""98"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""23"" endLine=""10"" endColumn=""40"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xb""> <local name=""x1"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInQuery_02() { var source = WithWindowsLineBreaks( @" using System.Linq; class C { C() #line 2000 { var q = from a in new [] {1} where G(out var x1) > F(() => x1) select a; } static int G(out int x) { throw null; } static int F(System.Func<int> x) { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C..ctor", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <closure offset=""88"" /> <lambda offset=""88"" /> <lambda offset=""112"" closure=""0"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""8"" document=""1"" /> <entry offset=""0x7"" startLine=""2000"" startColumn=""5"" endLine=""2000"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""2001"" startColumn=""9"" endLine=""2004"" endColumn=""26"" document=""1"" /> <entry offset=""0x37"" startLine=""2005"" startColumn=""5"" endLine=""2005"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x38""> <namespace name=""System.Linq"" /> <scope startOffset=""0x7"" endOffset=""0x38""> <local name=""q"" il_index=""0"" il_start=""0x7"" il_end=""0x38"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c.<.ctor>b__0_0", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c"" name=""&lt;.ctor&gt;b__0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> <encLocalSlotMap> <slot kind=""30"" offset=""88"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x6"" startLine=""2003"" startColumn=""23"" endLine=""2003"" endColumn=""50"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x25""> <local name=""CS$&lt;&gt;8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x25"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); c.VerifyPdb("C+<>c__DisplayClass0_0.<.ctor>b__1", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C+&lt;&gt;c__DisplayClass0_0"" name=""&lt;.ctor&gt;b__1""> <customDebugInfo> <forward declaringType=""C"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2003"" startColumn=""47"" endLine=""2003"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } [Fact] public void SyntaxOffset_OutVarInSwitchExpression() { var source = @"class C { static object G() => N(out var x) switch { null => x switch {1 => 1, _ => 2 }, _ => 1 }; static object N(out int x) { x = 1; return null; } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb("C.G", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""G""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""temp"" /> <slot kind=""35"" offset=""16"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0xb"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0xc"" hidden=""true"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""1"" startColumn=""64"" endLine=""1"" endColumn=""89"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x1b"" startLine=""1"" startColumn=""78"" endLine=""1"" endColumn=""79"" document=""1"" /> <entry offset=""0x1f"" startLine=""1"" startColumn=""86"" endLine=""1"" endColumn=""87"" document=""1"" /> <entry offset=""0x23"" hidden=""true"" document=""1"" /> <entry offset=""0x26"" startLine=""1"" startColumn=""45"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0x27"" startLine=""1"" startColumn=""62"" endLine=""1"" endColumn=""89"" document=""1"" /> <entry offset=""0x2b"" startLine=""1"" startColumn=""96"" endLine=""1"" endColumn=""97"" document=""1"" /> <entry offset=""0x2f"" hidden=""true"" document=""1"" /> <entry offset=""0x32"" startLine=""1"" startColumn=""32"" endLine=""1"" endColumn=""99"" document=""1"" /> <entry offset=""0x33"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x3a""> <local name=""x"" il_index=""0"" il_start=""0x0"" il_end=""0x3a"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } #endregion [WorkItem(4370, "https://github.com/dotnet/roslyn/issues/4370")] [Fact] public void HeadingHiddenSequencePointsPickUpDocumentFromVisibleSequencePoint() { var source = WithWindowsLineBreaks( @"#line 1 ""C:\Async.cs"" #pragma checksum ""C:\Async.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""DBEB2A067B2F0E0D678A002C587A2806056C3DCE"" using System.Threading.Tasks; public class C { public async void M1() { } } "); var tree = SyntaxFactory.ParseSyntaxTree(source, encoding: Encoding.UTF8, path: "HIDDEN.cs"); var c = CSharpCompilation.Create("Compilation", new[] { tree }, new[] { MscorlibRef_v46 }, options: TestOptions.DebugDll.WithDebugPlusMode(true)); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" /> <file id=""2"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" /> </files> <methods> <method containingType=""C"" name=""M1""> <customDebugInfo> <forwardIterator name=""&lt;M1&gt;d__0"" /> </customDebugInfo> </method> <method containingType=""C+&lt;M1&gt;d__0"" name=""MoveNext""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0xa"" hidden=""true"" document=""1"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x2a"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x37""> <namespace name=""System.Threading.Tasks"" /> </scope> <asyncInfo> <catchHandler offset=""0xa"" /> <kickoffMethod declaringType=""C"" methodName=""M1"" /> </asyncInfo> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""HIDDEN.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8A-92-EE-2F-D6-6F-C0-69-F4-A8-54-CB-11-BE-A3-06-76-2C-9C-98"" /> <file id=""2"" name=""C:\Async.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""DB-EB-2A-06-7B-2F-0E-0D-67-8A-00-2C-58-7A-28-06-05-6C-3D-CE"" /> </files> <methods> <method containingType=""C+&lt;M1&gt;d__0"" name=""MoveNext""> <customDebugInfo> <encLocalSlotMap> <slot kind=""27"" offset=""0"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""2"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""2"" /> <entry offset=""0xa"" hidden=""true"" document=""2"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""2"" /> <entry offset=""0x2a"" hidden=""true"" document=""2"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa"" /> <kickoffMethod declaringType=""C"" methodName=""M1"" /> </asyncInfo> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(12923, "https://github.com/dotnet/roslyn/issues/12923")] [Fact] public void SequencePointsForConstructorWithHiddenInitializer() { string initializerSource = WithWindowsLineBreaks(@" #line hidden partial class C { int i = 42; } "); string constructorSource = WithWindowsLineBreaks(@" partial class C { C() { } } "); var c = CreateCompilation( new[] { Parse(initializerSource, "initializer.cs"), Parse(constructorSource, "constructor.cs") }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" /> <file id=""2"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""1"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> ", format: DebugInformationFormat.Pdb); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""initializer.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""84-32-24-D7-FE-32-63-BA-41-D5-17-A2-D5-90-23-B8-12-3C-AF-D5"" /> <file id=""2"" name=""constructor.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""EA-D6-0A-16-6C-6A-BC-C1-5D-98-0F-B7-4B-78-13-93-FB-C7-C2-5A"" /> </files> <methods> <method containingType=""C"" name="".ctor""> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""2"" /> <entry offset=""0x8"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""8"" document=""2"" /> <entry offset=""0xf"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""2"" /> <entry offset=""0x10"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""2"" /> </sequencePoints> </method> </methods> </symbols>", format: DebugInformationFormat.PortablePdb); } [WorkItem(14437, "https://github.com/dotnet/roslyn/issues/14437")] [Fact] public void LocalFunctionSequencePoints() { string source = WithWindowsLineBreaks( @"class Program { static int Main(string[] args) { // 4 int Local1(string[] a) => a.Length; // 7 int Local2(string[] a) { // 9 return a.Length; // 10 } // 11 return Local1(args) + Local2(args); // 12 } // 13 }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <encLocalSlotMap> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""115"" /> <lambda offset=""202"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""44"" document=""1"" /> <entry offset=""0x13"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Program"" name=""&lt;Main&gt;g__Local1|0_0"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""21"" document=""1"" /> </sequencePoints> </method> <method containingType=""Program"" name=""&lt;Main&gt;g__Local2|0_1"" parameterNames=""a""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""202"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void SwitchInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { int i = 0; switch (i) { case 1: break; } } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 89 (0x59) .maxstack 2 .locals init (int V_0, int V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: switch (i) IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0016: stloc.1 // sequence point: <hidden> IL_0017: ldloc.1 IL_0018: stfld ""int Program.<Test>d__0.<>s__2"" // sequence point: <hidden> IL_001d: ldarg.0 IL_001e: ldfld ""int Program.<Test>d__0.<>s__2"" IL_0023: ldc.i4.1 IL_0024: beq.s IL_0028 IL_0026: br.s IL_002a // sequence point: break; IL_0028: br.s IL_002a // sequence point: <hidden> IL_002a: leave.s IL_0044 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_002c: stloc.2 IL_002d: ldarg.0 IL_002e: ldc.i4.s -2 IL_0030: stfld ""int Program.<Test>d__0.<>1__state"" IL_0035: ldarg.0 IL_0036: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_003b: ldloc.2 IL_003c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0041: nop IL_0042: leave.s IL_0058 } // sequence point: } IL_0044: ldarg.0 IL_0045: ldc.i4.s -2 IL_0047: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_004c: ldarg.0 IL_004d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0052: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0057: nop IL_0058: ret }", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void WhileInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { int i = 0; while (i == 1) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 83 (0x53) .maxstack 2 .locals init (int V_0, bool V_1, System.Exception V_2) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0; IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_000f: br.s IL_0017 // sequence point: Console.WriteLine(); IL_0011: call ""void System.Console.WriteLine()"" IL_0016: nop // sequence point: while (i == 1) IL_0017: ldarg.0 IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_001d: ldc.i4.1 IL_001e: ceq IL_0020: stloc.1 // sequence point: <hidden> IL_0021: ldloc.1 IL_0022: brtrue.s IL_0011 IL_0024: leave.s IL_003e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0026: stloc.2 IL_0027: ldarg.0 IL_0028: ldc.i4.s -2 IL_002a: stfld ""int Program.<Test>d__0.<>1__state"" IL_002f: ldarg.0 IL_0030: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0035: ldloc.2 IL_0036: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_003b: nop IL_003c: leave.s IL_0052 } // sequence point: } IL_003e: ldarg.0 IL_003f: ldc.i4.s -2 IL_0041: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0046: ldarg.0 IL_0047: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0051: nop IL_0052: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ForInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { for (int i = 0; i > 1; i--) Console.WriteLine(); } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 99 (0x63) .maxstack 3 .locals init (int V_0, int V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = 0 IL_0008: ldarg.0 IL_0009: ldc.i4.0 IL_000a: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_000f: br.s IL_0027 // sequence point: Console.WriteLine(); IL_0011: call ""void System.Console.WriteLine()"" IL_0016: nop // sequence point: i-- IL_0017: ldarg.0 IL_0018: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_001d: stloc.1 IL_001e: ldarg.0 IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: sub IL_0022: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: i > 1 IL_0027: ldarg.0 IL_0028: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_002d: ldc.i4.1 IL_002e: cgt IL_0030: stloc.2 // sequence point: <hidden> IL_0031: ldloc.2 IL_0032: brtrue.s IL_0011 IL_0034: leave.s IL_004e } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0036: stloc.3 IL_0037: ldarg.0 IL_0038: ldc.i4.s -2 IL_003a: stfld ""int Program.<Test>d__0.<>1__state"" IL_003f: ldarg.0 IL_0040: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0045: ldloc.3 IL_0046: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_004b: nop IL_004c: leave.s IL_0062 } // sequence point: } IL_004e: ldarg.0 IL_004f: ldc.i4.s -2 IL_0051: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0056: ldarg.0 IL_0057: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_005c: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_0061: nop IL_0062: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [Fact] [WorkItem(12564, "https://github.com/dotnet/roslyn/issues/12564")] public void ForWithInnerLocalsInAsyncMethod() { var source = @" using System; class Program { public static async void Test() { for (int i = M(out var x); i > 1; i--) Console.WriteLine(); } public static int M(out int x) { x = 0; return 0; } } "; var v = CompileAndVerify(source, options: TestOptions.DebugDll); v.VerifyIL("Program.<Test>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 109 (0x6d) .maxstack 3 .locals init (int V_0, int V_1, bool V_2, System.Exception V_3) // sequence point: <hidden> IL_0000: ldarg.0 IL_0001: ldfld ""int Program.<Test>d__0.<>1__state"" IL_0006: stloc.0 .try { // sequence point: { IL_0007: nop // sequence point: int i = M(out var x) IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: ldflda ""int Program.<Test>d__0.<x>5__2"" IL_000f: call ""int Program.M(out int)"" IL_0014: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: <hidden> IL_0019: br.s IL_0031 // sequence point: Console.WriteLine(); IL_001b: call ""void System.Console.WriteLine()"" IL_0020: nop // sequence point: i-- IL_0021: ldarg.0 IL_0022: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0027: stloc.1 IL_0028: ldarg.0 IL_0029: ldloc.1 IL_002a: ldc.i4.1 IL_002b: sub IL_002c: stfld ""int Program.<Test>d__0.<i>5__1"" // sequence point: i > 1 IL_0031: ldarg.0 IL_0032: ldfld ""int Program.<Test>d__0.<i>5__1"" IL_0037: ldc.i4.1 IL_0038: cgt IL_003a: stloc.2 // sequence point: <hidden> IL_003b: ldloc.2 IL_003c: brtrue.s IL_001b IL_003e: leave.s IL_0058 } catch System.Exception { // async: catch handler, sequence point: <hidden> IL_0040: stloc.3 IL_0041: ldarg.0 IL_0042: ldc.i4.s -2 IL_0044: stfld ""int Program.<Test>d__0.<>1__state"" IL_0049: ldarg.0 IL_004a: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_004f: ldloc.3 IL_0050: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_0055: nop IL_0056: leave.s IL_006c } // sequence point: } IL_0058: ldarg.0 IL_0059: ldc.i4.s -2 IL_005b: stfld ""int Program.<Test>d__0.<>1__state"" // sequence point: <hidden> IL_0060: ldarg.0 IL_0061: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Program.<Test>d__0.<>t__builder"" IL_0066: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_006b: nop IL_006c: ret } ", sequencePoints: "Program+<Test>d__0.MoveNext", source: source); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] [WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")] public void InvalidCharacterInPdbPath() { using (var outStream = Temp.CreateFile().Open()) { var compilation = CreateCompilation(""); var result = compilation.Emit(outStream, options: new EmitOptions(pdbFilePath: "test\\?.pdb", debugInformationFormat: DebugInformationFormat.Embedded)); // This is fine because EmitOptions just controls what is written into the PE file and it's // valid for this to be an illegal file name (path map can easily create these). Assert.True(result.Success); } } [Fact] [WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")] public void FilesOneWithNoMethodBody() { string source1 = WithWindowsLineBreaks(@" using System; class C { public static void Main() { Console.WriteLine(); } } "); string source2 = WithWindowsLineBreaks(@" // no code "); var tree1 = Parse(source1, "f:/build/goo.cs"); var tree2 = Parse(source2, "f:/build/nocode.cs"); var c = CreateCompilation(new[] { tree1, tree2 }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""f:/build/goo.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""5D-7D-CF-1B-79-12-0E-0A-80-13-E0-98-7E-5C-AA-3B-63-D8-7E-4F"" /> <file id=""2"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x8""> <namespace name=""System"" /> </scope> </method> </methods> </symbols> "); } [Fact] [WorkItem(38954, "https://github.com/dotnet/roslyn/issues/38954")] public void SingleFileWithNoMethodBody() { string source = WithWindowsLineBreaks(@" // no code "); var tree = Parse(source, "f:/build/nocode.cs"); var c = CreateCompilation(new[] { tree }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name=""f:/build/nocode.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""8B-1D-3F-75-E0-A8-8F-90-B2-D3-52-CF-71-9B-17-29-3C-70-7A-42"" /> </files> <methods /> </symbols> "); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/GenerateEqualsAndGetHashCodeFromMembersOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.GenerateEqualsAndGetHashCodeFromMembers { internal static class GenerateEqualsAndGetHashCodeFromMembersOptions { public static readonly PerLanguageOption2<bool> GenerateOperators = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(GenerateOperators), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}")); public static readonly PerLanguageOption2<bool> ImplementIEquatable = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(ImplementIEquatable), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}")); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.GenerateEqualsAndGetHashCodeFromMembers { internal static class GenerateEqualsAndGetHashCodeFromMembersOptions { public static readonly PerLanguageOption2<bool> GenerateOperators = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(GenerateOperators), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(GenerateOperators)}")); public static readonly PerLanguageOption2<bool> ImplementIEquatable = new( nameof(GenerateEqualsAndGetHashCodeFromMembersOptions), nameof(ImplementIEquatable), defaultValue: false, storageLocations: new RoamingProfileStorageLocation( $"TextEditor.%LANGUAGE%.Specific.{nameof(GenerateEqualsAndGetHashCodeFromMembersOptions)}.{nameof(ImplementIEquatable)}")); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/Collections/Enumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { public sealed class Enumerator : IEnumerator, ICloneable { internal static IEnumerator Create(Snapshot snapshot) { var newEnumerator = new Enumerator(snapshot); return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator); } private readonly Snapshot _snapshot; private int _currentItemIndex; private Enumerator(Snapshot snapshot) { _snapshot = snapshot; Reset(); } public object Current { get { return _snapshot[_currentItemIndex]; } } public bool MoveNext() { if (_currentItemIndex >= _snapshot.Count - 1) { return false; } _currentItemIndex++; return true; } public void Reset() => _currentItemIndex = -1; public object Clone() => Create(_snapshot); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { public sealed class Enumerator : IEnumerator, ICloneable { internal static IEnumerator Create(Snapshot snapshot) { var newEnumerator = new Enumerator(snapshot); return (IEnumerator)ComAggregate.CreateAggregatedObject(newEnumerator); } private readonly Snapshot _snapshot; private int _currentItemIndex; private Enumerator(Snapshot snapshot) { _snapshot = snapshot; Reset(); } public object Current { get { return _snapshot[_currentItemIndex]; } } public bool MoveNext() { if (_currentItemIndex >= _snapshot.Count - 1) { return false; } _currentItemIndex++; return true; } public void Reset() => _currentItemIndex = -1; public object Clone() => Create(_snapshot); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Symbols/SymbolExtensionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class SymbolExtensionTests : CSharpTestBase { [Fact] public void HasNameQualifier() { var source = @"class C { } namespace N { class C { } namespace NA { class C { } namespace NB { class C { } } } } namespace NA { class C { } namespace NA { class C { } } namespace NB { class C { } } } namespace NB { class C { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var namespaceNames = new[] { "", ".", "N", "NA", "NB", "n", "AN", "NAB", "N.", ".NA", ".NB", "N.N", "N.NA", "N.NB", "N..NB", "N.NA.NA", "N.NA.NB", "NA.N", "NA.NA", "NA.NB", "NA.NA.NB", "NA.NB.NB", }; HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("C"), ""); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.C"), "N"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.NA.C"), "N.NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.NA.NB.C"), "N.NA.NB"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.C"), "NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.NA.C"), "NA.NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.NB.C"), "NA.NB"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NB.C"), "NB"); } private void HasNameQualifierCore(string[] namespaceNames, NamedTypeSymbol type, string expectedName) { Assert.True(Array.IndexOf(namespaceNames, expectedName) >= 0); foreach (var namespaceName in namespaceNames) { Assert.Equal(namespaceName == expectedName, type.HasNameQualifier(namespaceName)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class SymbolExtensionTests : CSharpTestBase { [Fact] public void HasNameQualifier() { var source = @"class C { } namespace N { class C { } namespace NA { class C { } namespace NB { class C { } } } } namespace NA { class C { } namespace NA { class C { } } namespace NB { class C { } } } namespace NB { class C { } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); var namespaceNames = new[] { "", ".", "N", "NA", "NB", "n", "AN", "NAB", "N.", ".NA", ".NB", "N.N", "N.NA", "N.NB", "N..NB", "N.NA.NA", "N.NA.NB", "NA.N", "NA.NA", "NA.NB", "NA.NA.NB", "NA.NB.NB", }; HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("C"), ""); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.C"), "N"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.NA.C"), "N.NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("N.NA.NB.C"), "N.NA.NB"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.C"), "NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.NA.C"), "NA.NA"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NA.NB.C"), "NA.NB"); HasNameQualifierCore(namespaceNames, compilation.GetMember<NamedTypeSymbol>("NB.C"), "NB"); } private void HasNameQualifierCore(string[] namespaceNames, NamedTypeSymbol type, string expectedName) { Assert.True(Array.IndexOf(namespaceNames, expectedName) >= 0); foreach (var namespaceName in namespaceNames) { Assert.Equal(namespaceName == expectedName, type.HasNameQualifier(namespaceName)); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/Providers/AbstractPartialTypeCompletionProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractPartialTypeCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { protected AbstractPartialTypeCompletionProvider() { } public sealed override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken); if (node != null) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(node, cancellationToken).ConfigureAwait(false); if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is INamedTypeSymbol declaredSymbol) { var syntaxContextService = document.GetRequiredLanguageService<ISyntaxContextService>(); var syntaxContext = (TSyntaxContext)syntaxContextService.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken); var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken); var items = symbols?.Select(s => CreateCompletionItem(s, syntaxContext)); if (items != null) { completionContext.AddItems(items); } } } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private CompletionItem CreateCompletionItem(INamedTypeSymbol symbol, TSyntaxContext context) { var (displayText, suffix, insertionText) = GetDisplayAndSuffixAndInsertionText(symbol, context); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: suffix, insertionText: insertionText, symbols: ImmutableArray.Create(symbol), contextPosition: context.Position, properties: GetProperties(symbol, context), rules: CompletionItemRules.Default); } protected abstract ImmutableDictionary<string, string> GetProperties(INamedTypeSymbol symbol, TSyntaxContext context); protected abstract SyntaxNode GetPartialTypeSyntaxNode(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(INamedTypeSymbol symbol, TSyntaxContext context); protected virtual IEnumerable<INamedTypeSymbol> LookupCandidateSymbols(TSyntaxContext context, INamedTypeSymbol declaredSymbol, CancellationToken cancellationToken) { if (declaredSymbol == null) { throw new ArgumentNullException(nameof(declaredSymbol)); } var semanticModel = context.SemanticModel; if (declaredSymbol.ContainingSymbol is not INamespaceOrTypeSymbol containingSymbol) { return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>(); } return semanticModel.LookupNamespacesAndTypes(context.Position, containingSymbol) .OfType<INamedTypeSymbol>() .Where(symbol => declaredSymbol.TypeKind == symbol.TypeKind && NotNewDeclaredMember(symbol, context) && InSameProject(symbol, semanticModel.Compilation)); } private static bool InSameProject(INamedTypeSymbol symbol, Compilation compilation) => symbol.DeclaringSyntaxReferences.Any(r => compilation.SyntaxTrees.Contains(r.SyntaxTree)); private static bool NotNewDeclaredMember(INamedTypeSymbol symbol, TSyntaxContext context) { return symbol.DeclaringSyntaxReferences .Select(reference => reference.GetSyntax()) .Any(node => !(node.SyntaxTree == context.SyntaxTree && node.Span.IntersectsWith(context.Position))); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { var insertionText = SymbolCompletionItem.GetInsertionText(selectedItem); return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, insertionText)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractPartialTypeCompletionProvider<TSyntaxContext> : LSPCompletionProvider where TSyntaxContext : SyntaxContext { protected AbstractPartialTypeCompletionProvider() { } public sealed override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var node = GetPartialTypeSyntaxNode(tree, position, cancellationToken); if (node != null) { var semanticModel = await document.ReuseExistingSpeculativeModelAsync(node, cancellationToken).ConfigureAwait(false); if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is INamedTypeSymbol declaredSymbol) { var syntaxContextService = document.GetRequiredLanguageService<ISyntaxContextService>(); var syntaxContext = (TSyntaxContext)syntaxContextService.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken); var symbols = LookupCandidateSymbols(syntaxContext, declaredSymbol, cancellationToken); var items = symbols?.Select(s => CreateCompletionItem(s, syntaxContext)); if (items != null) { completionContext.AddItems(items); } } } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private CompletionItem CreateCompletionItem(INamedTypeSymbol symbol, TSyntaxContext context) { var (displayText, suffix, insertionText) = GetDisplayAndSuffixAndInsertionText(symbol, context); return SymbolCompletionItem.CreateWithSymbolId( displayText: displayText, displayTextSuffix: suffix, insertionText: insertionText, symbols: ImmutableArray.Create(symbol), contextPosition: context.Position, properties: GetProperties(symbol, context), rules: CompletionItemRules.Default); } protected abstract ImmutableDictionary<string, string> GetProperties(INamedTypeSymbol symbol, TSyntaxContext context); protected abstract SyntaxNode GetPartialTypeSyntaxNode(SyntaxTree tree, int position, CancellationToken cancellationToken); protected abstract (string displayText, string suffix, string insertionText) GetDisplayAndSuffixAndInsertionText(INamedTypeSymbol symbol, TSyntaxContext context); protected virtual IEnumerable<INamedTypeSymbol> LookupCandidateSymbols(TSyntaxContext context, INamedTypeSymbol declaredSymbol, CancellationToken cancellationToken) { if (declaredSymbol == null) { throw new ArgumentNullException(nameof(declaredSymbol)); } var semanticModel = context.SemanticModel; if (declaredSymbol.ContainingSymbol is not INamespaceOrTypeSymbol containingSymbol) { return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>(); } return semanticModel.LookupNamespacesAndTypes(context.Position, containingSymbol) .OfType<INamedTypeSymbol>() .Where(symbol => declaredSymbol.TypeKind == symbol.TypeKind && NotNewDeclaredMember(symbol, context) && InSameProject(symbol, semanticModel.Compilation)); } private static bool InSameProject(INamedTypeSymbol symbol, Compilation compilation) => symbol.DeclaringSyntaxReferences.Any(r => compilation.SyntaxTrees.Contains(r.SyntaxTree)); private static bool NotNewDeclaredMember(INamedTypeSymbol symbol, TSyntaxContext context) { return symbol.DeclaringSyntaxReferences .Select(reference => reference.GetSyntax()) .Any(node => !(node.SyntaxTree == context.SyntaxTree && node.Span.IntersectsWith(context.Position))); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); public override Task<TextChange?> GetTextChangeAsync(Document document, CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { var insertionText = SymbolCompletionItem.GetInsertionText(selectedItem); return Task.FromResult<TextChange?>(new TextChange(selectedItem.Span, insertionText)); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test2/NavigationBar/CSharpNavigationBarTests.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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class CSharpNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545021")> Public Async Function TestGenericTypeVariance(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[interface C<in I, out O> { }]]></Document> </Project> </Workspace>, host, Item("C<in I, out O>", Glyph.InterfaceInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545284")> Public Async Function TestGenericMember(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[class Program { static void Swap<T>(T lhs, T rhs) { }}]]></Document> </Project> </Workspace>, host, Item("Program", Glyph.ClassInternal, children:={ Item("Swap<T>(T lhs, T rhs)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestNestedClasses(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { } }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={}), Item("C.Nested", Glyph.ClassPrivate, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { $$ } }</Document> </Project> </Workspace>, host, Item("C.Nested", Glyph.ClassPrivate), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545019")> Public Async Function TestSelectedItemForEnumAfterComma(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>enum E { A,$$ B }</Document> </Project> </Workspace>, host, Item("E", Glyph.EnumInternal), False, Item("A", Glyph.EnumMemberPublic), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldAfterSemicolon(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo;$$ }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldInType(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { in$$t goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545267")> Public Async Function TestSelectedItemAtEndOfFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo; } $$</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), True, Item("goo", Glyph.FieldPrivate), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545012")> Public Async Function TestExplicitInterfaceImplementation(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : IDisposable { void IDisposable.Dispose() { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("IDisposable.Dispose()", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545007")> Public Async Function TestRefAndOutParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(out string goo, ref string bar) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(out string goo, ref string bar)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545001")> Public Async Function TestOptionalParameter(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(int i = 0) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(int i = 0)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestOptionalParameter2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(CancellationToken cancellationToken = default)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545274")> Public Async Function TestProperties(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private int Number { get; set; } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("Number", Glyph.PropertyPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum Goo { A, B, C } </Document> </Project> </Workspace>, host, Item("Goo", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void Goo(); </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestPartialClassWithFieldInOtherFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$ }</Document> <Document>partial class C { int goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate, grayed:=True), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$partial void M(); }</Document> <Document>partial class C { partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { partial void M(); }</Document> <Document>partial class C { $$partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$public partial void M(); }</Document> <Document>partial class C { public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { public partial void M(); }</Document> <Document>partial class C { $$public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37183, "https://github.com/dotnet/roslyn/issues/37183")> Public Async Function TestNullableReferenceTypesInParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>#nullable enable using System.Collections.Generic; class C { void M(string? s, IEnumerable&lt;string?&gt; e) { }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(string? s, IEnumerable<string?> e)", Glyph.MethodPrivate)})) 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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar <[UseExportProvider]> Partial Public Class CSharpNavigationBarTests <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545021")> Public Async Function TestGenericTypeVariance(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[interface C<in I, out O> { }]]></Document> </Project> </Workspace>, host, Item("C<in I, out O>", Glyph.InterfaceInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545284, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545284")> Public Async Function TestGenericMember(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[class Program { static void Swap<T>(T lhs, T rhs) { }}]]></Document> </Project> </Workspace>, host, Item("Program", Glyph.ClassInternal, children:={ Item("Swap<T>(T lhs, T rhs)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestNestedClasses(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { } }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={}), Item("C.Nested", Glyph.ClassPrivate, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545023")> Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { class Nested { $$ } }</Document> </Project> </Workspace>, host, Item("C.Nested", Glyph.ClassPrivate), False, Nothing, False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545019")> Public Async Function TestSelectedItemForEnumAfterComma(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>enum E { A,$$ B }</Document> </Project> </Workspace>, host, Item("E", Glyph.EnumInternal), False, Item("A", Glyph.EnumMemberPublic), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldAfterSemicolon(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo;$$ }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestSelectedItemForFieldInType(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { in$$t goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate), False) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545267")> Public Async Function TestSelectedItemAtEndOfFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class C { int goo; } $$</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), True, Item("goo", Glyph.FieldPrivate), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545012")> Public Async Function TestExplicitInterfaceImplementation(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C : IDisposable { void IDisposable.Dispose() { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("IDisposable.Dispose()", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545007")> Public Async Function TestRefAndOutParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(out string goo, ref string bar) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(out string goo, ref string bar)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545001")> Public Async Function TestOptionalParameter(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(int i = 0) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(int i = 0)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)> Public Async Function TestOptionalParameter2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(CancellationToken cancellationToken = default)", Glyph.MethodPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545274")> Public Async Function TestProperties(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { private int Number { get; set; } } </Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("Number", Glyph.PropertyPrivate)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestEnum(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum Goo { A, B, C } </Document> </Project> </Workspace>, host, Item("Goo", Glyph.EnumInternal, children:={ Item("A", Glyph.EnumMemberPublic), Item("B", Glyph.EnumMemberPublic), Item("C", Glyph.EnumMemberPublic)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")> Public Async Function TestDelegate(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void Goo(); </Document> </Project> </Workspace>, host, Item("Goo", Glyph.DelegateInternal, children:={})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545114")> Public Async Function TestPartialClassWithFieldInOtherFile(host As TestHost) As Task Await AssertSelectedItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$ }</Document> <Document>partial class C { int goo; }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal), False, Item("goo", Glyph.FieldPrivate, grayed:=True), True) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$partial void M(); }</Document> <Document>partial class C { partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { partial void M(); }</Document> <Document>partial class C { $$partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPrivate), Item("M()", Glyph.MethodPrivate, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts1(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { $$public partial void M(); }</Document> <Document>partial class C { public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(578100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578100")> Public Async Function TestPartialClassWithBothExtendedPartialMethodParts2(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>partial class C { public partial void M(); }</Document> <Document>partial class C { $$public partial void M(){} }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M()", Glyph.MethodPublic), Item("M()", Glyph.MethodPublic, grayed:=True)})) End Function <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37183, "https://github.com/dotnet/roslyn/issues/37183")> Public Async Function TestNullableReferenceTypesInParameters(host As TestHost) As Task Await AssertItemsAreAsync( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>#nullable enable using System.Collections.Generic; class C { void M(string? s, IEnumerable&lt;string?&gt; e) { }</Document> </Project> </Workspace>, host, Item("C", Glyph.ClassInternal, children:={ Item("M(string? s, IEnumerable<string?> e)", Glyph.MethodPrivate)})) End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/D.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. ' vbc /t:library /vbruntime- D.vb Imports System.Collections.Generic Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b5826D")> <Assembly: ImportedFromTypeLib("D.dll")> <ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f200D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ID End Interface
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. ' vbc /t:library /vbruntime- D.vb Imports System.Collections.Generic Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices <Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b5826D")> <Assembly: ImportedFromTypeLib("D.dll")> <ComImport(), Guid("27e3e649-994b-4f58-b3c6-f8089a5f200D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface ID End Interface
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Completion/ExportArgumentProviderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.Completion { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportArgumentProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportArgumentProviderAttribute(string name, string language) : base(typeof(ArgumentProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); Roles = Array.Empty<string>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; namespace Microsoft.CodeAnalysis.Completion { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal sealed class ExportArgumentProviderAttribute : ExportAttribute { public string Name { get; } public string Language { get; } public string[] Roles { get; set; } public ExportArgumentProviderAttribute(string name, string language) : base(typeof(ArgumentProvider)) { Name = name ?? throw new ArgumentNullException(nameof(name)); Language = language ?? throw new ArgumentNullException(nameof(language)); Roles = Array.Empty<string>(); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/MakeRefStruct/MakeRefStructCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.MakeRefStruct { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeRefStruct), Shared] internal class MakeRefStructCodeFixProvider : CodeFixProvider { // Error CS8345: Field or auto-implemented property cannot be of certain type unless it is an instance member of a ref struct. private const string CS8345 = nameof(CS8345); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeRefStructCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS8345); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var structDeclaration = FindContainingStruct(root, span); if (structDeclaration == null) { return; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration, cancellationToken); // CS8345 could be triggered when struct is already marked with `ref` but a property is static if (!structDeclarationSymbol.IsRefLikeType) { context.RegisterCodeFix( new MyCodeAction(c => FixCodeAsync(document, structDeclaration, c)), context.Diagnostics); } } public override FixAllProvider GetFixAllProvider() { // The chance of needing fix-all in these cases is super low return null; } private static async Task<Document> FixCodeAsync( Document document, StructDeclarationSyntax structDeclaration, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newStruct = generator.WithModifiers( structDeclaration, generator.GetModifiers(structDeclaration).WithIsRef(true)); var newRoot = root.ReplaceNode(structDeclaration, newStruct); return document.WithSyntaxRoot(newRoot); } private static StructDeclarationSyntax FindContainingStruct(SyntaxNode root, TextSpan span) { var member = root.FindNode(span); // Could be declared in a class or even in a nested class inside a struct, // so find only the first parent declaration return member.GetAncestor<TypeDeclarationSyntax>() as StructDeclarationSyntax; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Make_ref_struct, createChangedDocument, CSharpFeaturesResources.Make_ref_struct) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.MakeRefStruct { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeRefStruct), Shared] internal class MakeRefStructCodeFixProvider : CodeFixProvider { // Error CS8345: Field or auto-implemented property cannot be of certain type unless it is an instance member of a ref struct. private const string CS8345 = nameof(CS8345); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeRefStructCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS8345); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var structDeclaration = FindContainingStruct(root, span); if (structDeclaration == null) { return; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var structDeclarationSymbol = semanticModel.GetDeclaredSymbol(structDeclaration, cancellationToken); // CS8345 could be triggered when struct is already marked with `ref` but a property is static if (!structDeclarationSymbol.IsRefLikeType) { context.RegisterCodeFix( new MyCodeAction(c => FixCodeAsync(document, structDeclaration, c)), context.Diagnostics); } } public override FixAllProvider GetFixAllProvider() { // The chance of needing fix-all in these cases is super low return null; } private static async Task<Document> FixCodeAsync( Document document, StructDeclarationSyntax structDeclaration, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var generator = SyntaxGenerator.GetGenerator(document); var newStruct = generator.WithModifiers( structDeclaration, generator.GetModifiers(structDeclaration).WithIsRef(true)); var newRoot = root.ReplaceNode(structDeclaration, newStruct); return document.WithSyntaxRoot(newRoot); } private static StructDeclarationSyntax FindContainingStruct(SyntaxNode root, TextSpan span) { var member = root.FindNode(span); // Could be declared in a class or even in a nested class inside a struct, // so find only the first parent declaration return member.GetAncestor<TypeDeclarationSyntax>() as StructDeclarationSyntax; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Make_ref_struct, createChangedDocument, CSharpFeaturesResources.Make_ref_struct) { } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/CodeCleanup/AbstractCodeCleanupFixerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup { internal abstract class AbstractCodeCleanUpFixerProvider : ICodeCleanUpFixerProvider { private readonly ImmutableArray<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> _codeCleanUpFixers; protected AbstractCodeCleanUpFixerProvider( IEnumerable<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> codeCleanUpFixers) { _codeCleanUpFixers = codeCleanUpFixers.ToImmutableArray(); } public IReadOnlyCollection<ICodeCleanUpFixer> GetFixers() => _codeCleanUpFixers.SelectAsArray(lazyFixer => lazyFixer.Value); public IReadOnlyCollection<ICodeCleanUpFixer> GetFixers(IContentType contentType) => _codeCleanUpFixers.WhereAsArray(handler => handler.Metadata.ContentTypes.Any(contentType.IsOfType)) .SelectAsArray(l => l.Value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Language.CodeCleanUp; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeCleanup { internal abstract class AbstractCodeCleanUpFixerProvider : ICodeCleanUpFixerProvider { private readonly ImmutableArray<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> _codeCleanUpFixers; protected AbstractCodeCleanUpFixerProvider( IEnumerable<Lazy<AbstractCodeCleanUpFixer, ContentTypeMetadata>> codeCleanUpFixers) { _codeCleanUpFixers = codeCleanUpFixers.ToImmutableArray(); } public IReadOnlyCollection<ICodeCleanUpFixer> GetFixers() => _codeCleanUpFixers.SelectAsArray(lazyFixer => lazyFixer.Value); public IReadOnlyCollection<ICodeCleanUpFixer> GetFixers(IContentType contentType) => _codeCleanUpFixers.WhereAsArray(handler => handler.Metadata.ContentTypes.Any(contentType.IsOfType)) .SelectAsArray(l => l.Value); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/LogMessage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(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. using System; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// log message that can generate string lazily /// </summary> internal abstract class LogMessage { public LogLevel LogLevel { get; protected set; } = LogLevel.Debug; public static LogMessage Create(string message, LogLevel logLevel) => StaticLogMessage.Construct(message, logLevel); public static LogMessage Create(Func<string> messageGetter, LogLevel logLevel) => LazyLogMessage.Construct(messageGetter, logLevel); public static LogMessage Create<TArg>(Func<TArg, string> messageGetter, TArg arg, LogLevel logLevel) => LazyLogMessage<TArg>.Construct(messageGetter, arg, logLevel); public static LogMessage Create<TArg0, TArg1>(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1>.Construct(messageGetter, arg0, arg1, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2>(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2>.Construct(messageGetter, arg0, arg1, arg2, logLevel); public static LogMessage Create<TArg0, TArg1, TArg2, TArg3>(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) => LazyLogMessage<TArg0, TArg1, TArg2, TArg3>.Construct(messageGetter, arg0, arg1, arg2, arg3, logLevel); // message will be either initially set or lazily set by caller private string? _message; protected abstract string CreateMessage(); /// <summary> /// Logger will call this to return LogMessage to its pool /// </summary> protected abstract void FreeCore(); public string GetMessage() { if (_message == null) { _message = CreateMessage(); } return _message; } public void Free() { _message = null; FreeCore(); } private sealed class StaticLogMessage : LogMessage { private static readonly ObjectPool<StaticLogMessage> s_pool = SharedPools.Default<StaticLogMessage>(); public static LogMessage Construct(string message, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._message = message; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _message!; protected override void FreeCore() { if (_message == null) { return; } _message = null; s_pool.Free(this); } } private sealed class LazyLogMessage : LogMessage { private static readonly ObjectPool<LazyLogMessage> s_pool = SharedPools.Default<LazyLogMessage>(); private Func<string>? _messageGetter; public static LogMessage Construct(Func<string> messageGetter, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0>> s_pool = SharedPools.Default<LazyLogMessage<TArg0>>(); private Func<TArg0, string>? _messageGetter; private TArg0? _arg; public static LogMessage Construct(Func<TArg0, string> messageGetter, TArg0 arg, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg = arg; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1>>(); private Func<TArg0, TArg1, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; internal static LogMessage Construct(Func<TArg0, TArg1, string> messageGetter, TArg0 arg0, TArg1 arg1, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2>>(); private Func<TArg0, TArg1, TArg2, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; s_pool.Free(this); } } private sealed class LazyLogMessage<TArg0, TArg1, TArg2, TArg3> : LogMessage { private static readonly ObjectPool<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>> s_pool = SharedPools.Default<LazyLogMessage<TArg0, TArg1, TArg2, TArg3>>(); private Func<TArg0, TArg1, TArg2, TArg3, string>? _messageGetter; private TArg0? _arg0; private TArg1? _arg1; private TArg2? _arg2; private TArg3? _arg3; public static LogMessage Construct(Func<TArg0, TArg1, TArg2, TArg3, string> messageGetter, TArg0 arg0, TArg1 arg1, TArg2 arg2, TArg3 arg3, LogLevel logLevel) { var logMessage = s_pool.Allocate(); logMessage._messageGetter = messageGetter; logMessage._arg0 = arg0; logMessage._arg1 = arg1; logMessage._arg2 = arg2; logMessage._arg3 = arg3; logMessage.LogLevel = logLevel; return logMessage; } protected override string CreateMessage() => _messageGetter!(_arg0!, _arg1!, _arg2!, _arg3!); protected override void FreeCore() { if (_messageGetter == null) { return; } _messageGetter = null; _arg0 = default; _arg1 = default; _arg2 = default; _arg3 = default; s_pool.Free(this); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/LiveShare/Impl/Client/Projects/RoslynRemoteProjectInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { [Export(typeof(IRemoteProjectInfoProvider))] internal class RoslynRemoteProjectInfoProvider : IRemoteProjectInfoProvider { private const string SystemUriSchemeExternal = "vslsexternal"; private readonly string[] _secondaryBufferFileExtensions = new string[] { ".cshtml", ".razor", ".html", ".aspx", ".vue" }; private readonly CSharpLspClientServiceFactory _roslynLspClientServiceFactory; private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynRemoteProjectInfoProvider(CSharpLspClientServiceFactory roslynLspClientServiceFactory, RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _roslynLspClientServiceFactory = roslynLspClientServiceFactory ?? throw new ArgumentNullException(nameof(roslynLspClientServiceFactory)); _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace ?? throw new ArgumentNullException(nameof(RemoteLanguageServiceWorkspace)); } public async Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken) { if (!_remoteLanguageServiceWorkspace.IsRemoteSession) { return ImmutableArray<ProjectInfo>.Empty; } var lspClient = _roslynLspClientServiceFactory.ActiveLanguageServerClient; if (lspClient == null) { return ImmutableArray<ProjectInfo>.Empty; } CustomProtocol.Project[] projects; try { var request = new LspRequest<object, CustomProtocol.Project[]>(CustomProtocol.RoslynMethods.ProjectsName); projects = await lspClient.RequestAsync(request, new object(), cancellationToken).ConfigureAwait(false); } catch (Exception) { projects = null; } if (projects == null) { return ImmutableArray<ProjectInfo>.Empty; } var projectInfos = ImmutableArray.CreateBuilder<ProjectInfo>(); foreach (var project in projects) { // We don't want to add cshtml files to the workspace since the Roslyn will add the generated secondary buffer of a cshtml // file to a different project but with the same path. This used to be ok in Dev15 but in Dev16 this confuses Roslyn and causes downstream // issues. There's no need to add the actual cshtml file to the workspace - so filter those out. // This is also the case for files for which TypeScript adds the generated TypeScript buffer to a different project. var filesTasks = project.SourceFiles .Where(f => f.Scheme != SystemUriSchemeExternal) .Where(f => !this._secondaryBufferFileExtensions.Any(ext => f.LocalPath.EndsWith(ext))) .Select(f => lspClient.ProtocolConverter.FromProtocolUriAsync(f, false, cancellationToken)); var files = await Task.WhenAll(filesTasks).ConfigureAwait(false); var projectInfo = CreateProjectInfo(project.Name, project.Language, files.Select(f => f.LocalPath).ToImmutableArray()); projectInfos.Add(projectInfo); } return projectInfos.ToImmutableArray(); } private static ProjectInfo CreateProjectInfo(string projectName, string language, ImmutableArray<string> files) { var projectId = ProjectId.CreateNewId(); var docInfos = ImmutableArray.CreateBuilder<DocumentInfo>(); foreach (var file in files) { var fileName = Path.GetFileNameWithoutExtension(file); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), fileName, filePath: file, loader: new FileTextLoaderNoException(file, null)); docInfos.Add(docInfo); } return ProjectInfo.Create( projectId, VersionStamp.Create(), projectName, projectName, language, documents: docInfos.ToImmutable()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { [Export(typeof(IRemoteProjectInfoProvider))] internal class RoslynRemoteProjectInfoProvider : IRemoteProjectInfoProvider { private const string SystemUriSchemeExternal = "vslsexternal"; private readonly string[] _secondaryBufferFileExtensions = new string[] { ".cshtml", ".razor", ".html", ".aspx", ".vue" }; private readonly CSharpLspClientServiceFactory _roslynLspClientServiceFactory; private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RoslynRemoteProjectInfoProvider(CSharpLspClientServiceFactory roslynLspClientServiceFactory, RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _roslynLspClientServiceFactory = roslynLspClientServiceFactory ?? throw new ArgumentNullException(nameof(roslynLspClientServiceFactory)); _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace ?? throw new ArgumentNullException(nameof(RemoteLanguageServiceWorkspace)); } public async Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken) { if (!_remoteLanguageServiceWorkspace.IsRemoteSession) { return ImmutableArray<ProjectInfo>.Empty; } var lspClient = _roslynLspClientServiceFactory.ActiveLanguageServerClient; if (lspClient == null) { return ImmutableArray<ProjectInfo>.Empty; } CustomProtocol.Project[] projects; try { var request = new LspRequest<object, CustomProtocol.Project[]>(CustomProtocol.RoslynMethods.ProjectsName); projects = await lspClient.RequestAsync(request, new object(), cancellationToken).ConfigureAwait(false); } catch (Exception) { projects = null; } if (projects == null) { return ImmutableArray<ProjectInfo>.Empty; } var projectInfos = ImmutableArray.CreateBuilder<ProjectInfo>(); foreach (var project in projects) { // We don't want to add cshtml files to the workspace since the Roslyn will add the generated secondary buffer of a cshtml // file to a different project but with the same path. This used to be ok in Dev15 but in Dev16 this confuses Roslyn and causes downstream // issues. There's no need to add the actual cshtml file to the workspace - so filter those out. // This is also the case for files for which TypeScript adds the generated TypeScript buffer to a different project. var filesTasks = project.SourceFiles .Where(f => f.Scheme != SystemUriSchemeExternal) .Where(f => !this._secondaryBufferFileExtensions.Any(ext => f.LocalPath.EndsWith(ext))) .Select(f => lspClient.ProtocolConverter.FromProtocolUriAsync(f, false, cancellationToken)); var files = await Task.WhenAll(filesTasks).ConfigureAwait(false); var projectInfo = CreateProjectInfo(project.Name, project.Language, files.Select(f => f.LocalPath).ToImmutableArray()); projectInfos.Add(projectInfo); } return projectInfos.ToImmutableArray(); } private static ProjectInfo CreateProjectInfo(string projectName, string language, ImmutableArray<string> files) { var projectId = ProjectId.CreateNewId(); var docInfos = ImmutableArray.CreateBuilder<DocumentInfo>(); foreach (var file in files) { var fileName = Path.GetFileNameWithoutExtension(file); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(projectId), fileName, filePath: file, loader: new FileTextLoaderNoException(file, null)); docInfos.Add(docInfo); } return ProjectInfo.Create( projectId, VersionStamp.Create(), projectName, projectName, language, documents: docInfos.ToImmutable()); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.DocumentHighlighting { [ExportLanguageService(typeof(IDocumentHighlightsService), LanguageNames.CSharp), Shared] internal class CSharpDocumentHighlightsService : AbstractDocumentHighlightsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentHighlightsService() { } protected override async Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { // The FindRefs engine won't find references through 'var' for performance reasons. // Also, they are not needed for things like rename/sig change, and the normal find refs // feature. However, we would like the results to be highlighted to get a good experience // while editing (especially since highlighting may have been invoked off of 'var' in // the first place). // // So we look for the references through 'var' directly in this file and add them to the // results found by the engine. var results = ArrayBuilder<Location>.GetInstance(); if (symbol is INamedTypeSymbol && symbol.Name != "var") { var originalSymbol = symbol.OriginalDefinition; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var descendents = root.DescendantNodes(); var semanticModel = (SemanticModel)null; foreach (var type in descendents.OfType<IdentifierNameSyntax>()) { cancellationToken.ThrowIfCancellationRequested(); if (type.IsVar) { if (semanticModel == null) { semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); } var boundSymbol = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol; boundSymbol = boundSymbol?.OriginalDefinition; if (originalSymbol.Equals(boundSymbol)) { results.Add(type.GetLocation()); } } } } return results.ToImmutableAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.DocumentHighlighting { [ExportLanguageService(typeof(IDocumentHighlightsService), LanguageNames.CSharp), Shared] internal class CSharpDocumentHighlightsService : AbstractDocumentHighlightsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentHighlightsService() { } protected override async Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { // The FindRefs engine won't find references through 'var' for performance reasons. // Also, they are not needed for things like rename/sig change, and the normal find refs // feature. However, we would like the results to be highlighted to get a good experience // while editing (especially since highlighting may have been invoked off of 'var' in // the first place). // // So we look for the references through 'var' directly in this file and add them to the // results found by the engine. var results = ArrayBuilder<Location>.GetInstance(); if (symbol is INamedTypeSymbol && symbol.Name != "var") { var originalSymbol = symbol.OriginalDefinition; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var descendents = root.DescendantNodes(); var semanticModel = (SemanticModel)null; foreach (var type in descendents.OfType<IdentifierNameSyntax>()) { cancellationToken.ThrowIfCancellationRequested(); if (type.IsVar) { if (semanticModel == null) { semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); } var boundSymbol = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol; boundSymbol = boundSymbol?.OriginalDefinition; if (originalSymbol.Equals(boundSymbol)) { results.Add(type.GetLocation()); } } } } return results.ToImmutableAndFree(); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/TextEditApplication.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class TextEditApplication { internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); var changes = newText.GetTextChanges(oldText); UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options); } public static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); UpdateText(textChanges, buffer, oldSnapshot, oldText, options); } private static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options) { using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null); if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace)) { var undoService = workspace.Services.GetRequiredService<ISourceTextUndoService>(); undoService.BeginUndoTransaction(oldSnapshot); } foreach (var change in textChanges) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.ApplyAndLogExceptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal static class TextEditApplication { internal static void UpdateText(SourceText newText, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); var changes = newText.GetTextChanges(oldText); UpdateText(changes.ToImmutableArray(), buffer, oldSnapshot, oldText, options); } public static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, EditOptions options) { var oldSnapshot = buffer.CurrentSnapshot; var oldText = oldSnapshot.AsText(); UpdateText(textChanges, buffer, oldSnapshot, oldText, options); } private static void UpdateText(ImmutableArray<TextChange> textChanges, ITextBuffer buffer, ITextSnapshot oldSnapshot, SourceText oldText, EditOptions options) { using var edit = buffer.CreateEdit(options, reiteratedVersionNumber: null, editTag: null); if (CodeAnalysis.Workspace.TryGetWorkspace(oldText.Container, out var workspace)) { var undoService = workspace.Services.GetRequiredService<ISourceTextUndoService>(); undoService.BeginUndoTransaction(oldSnapshot); } foreach (var change in textChanges) { edit.Replace(change.Span.Start, change.Span.Length, change.NewText); } edit.ApplyAndLogExceptions(); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/LegacyDiagnosticItemSource.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class LegacyDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource { private readonly AnalyzerItem _item; public LegacyDiagnosticItemSource(AnalyzerItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService diagnosticAnalyzerService) : base(item.AnalyzersFolder.Workspace, item.AnalyzersFolder.ProjectId, commandHandler, diagnosticAnalyzerService) { _item = item; } public override object SourceItem => _item; public override AnalyzerReference AnalyzerReference => _item.AnalyzerReference; } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class LegacyDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource { private readonly AnalyzerItem _item; public LegacyDiagnosticItemSource(AnalyzerItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService diagnosticAnalyzerService) : base(item.AnalyzersFolder.Workspace, item.AnalyzersFolder.ProjectId, commandHandler, diagnosticAnalyzerService) { _item = item; } public override object SourceItem => _item; public override AnalyzerReference AnalyzerReference => _item.AnalyzerReference; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.CompilationManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Return CompilationWithAnalyzer for given project with given stateSets /// </summary> private async Task<CompilationWithAnalyzers?> GetOrCreateCompilationWithAnalyzersAsync(Project project, IEnumerable<StateSet> stateSets, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return null; } if (_projectCompilationsWithAnalyzers.TryGetValue(project, out var compilationWithAnalyzers)) { // we have cached one, return that. AssertAnalyzers(compilationWithAnalyzers, stateSets); return compilationWithAnalyzers; } // Create driver that holds onto compilation and associated analyzers var includeSuppressedDiagnostics = true; var newCompilationWithAnalyzers = await CreateCompilationWithAnalyzersAsync(project, stateSets, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); // Add new analyzer driver to the map compilationWithAnalyzers = _projectCompilationsWithAnalyzers.GetValue(project, _ => newCompilationWithAnalyzers); // if somebody has beat us, make sure analyzers are good. if (compilationWithAnalyzers != newCompilationWithAnalyzers) { AssertAnalyzers(compilationWithAnalyzers, stateSets); } return compilationWithAnalyzers; } private static Task<CompilationWithAnalyzers?> CreateCompilationWithAnalyzersAsync(Project project, IEnumerable<StateSet> stateSets, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, stateSets.Select(s => s.Analyzer), includeSuppressedDiagnostics, cancellationToken); private void ClearCompilationsWithAnalyzersCache(Project project) => _projectCompilationsWithAnalyzers.Remove(project); private void ClearCompilationsWithAnalyzersCache() { // we basically eagarly clear the cache on some known changes // to let CompilationWithAnalyzer go. // we create new conditional weak table every time, it turns out // only way to clear ConditionalWeakTable is re-creating it. // also, conditional weak table has a leak - https://github.com/dotnet/coreclr/issues/665 _projectCompilationsWithAnalyzers = new ConditionalWeakTable<Project, CompilationWithAnalyzers?>(); } [Conditional("DEBUG")] private static void AssertAnalyzers(CompilationWithAnalyzers? compilation, IEnumerable<StateSet> stateSets) { if (compilation == null) { // this can happen if project doesn't support compilation or no stateSets are given. return; } // make sure analyzers are same. Contract.ThrowIfFalse(compilation.Analyzers.SetEquals(stateSets.Select(s => s.Analyzer).Where(a => !a.IsWorkspaceDiagnosticAnalyzer()))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// Return CompilationWithAnalyzer for given project with given stateSets /// </summary> private async Task<CompilationWithAnalyzers?> GetOrCreateCompilationWithAnalyzersAsync(Project project, IEnumerable<StateSet> stateSets, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return null; } if (_projectCompilationsWithAnalyzers.TryGetValue(project, out var compilationWithAnalyzers)) { // we have cached one, return that. AssertAnalyzers(compilationWithAnalyzers, stateSets); return compilationWithAnalyzers; } // Create driver that holds onto compilation and associated analyzers var includeSuppressedDiagnostics = true; var newCompilationWithAnalyzers = await CreateCompilationWithAnalyzersAsync(project, stateSets, includeSuppressedDiagnostics, cancellationToken).ConfigureAwait(false); // Add new analyzer driver to the map compilationWithAnalyzers = _projectCompilationsWithAnalyzers.GetValue(project, _ => newCompilationWithAnalyzers); // if somebody has beat us, make sure analyzers are good. if (compilationWithAnalyzers != newCompilationWithAnalyzers) { AssertAnalyzers(compilationWithAnalyzers, stateSets); } return compilationWithAnalyzers; } private static Task<CompilationWithAnalyzers?> CreateCompilationWithAnalyzersAsync(Project project, IEnumerable<StateSet> stateSets, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) => AnalyzerHelper.CreateCompilationWithAnalyzersAsync(project, stateSets.Select(s => s.Analyzer), includeSuppressedDiagnostics, cancellationToken); private void ClearCompilationsWithAnalyzersCache(Project project) => _projectCompilationsWithAnalyzers.Remove(project); private void ClearCompilationsWithAnalyzersCache() { // we basically eagarly clear the cache on some known changes // to let CompilationWithAnalyzer go. // we create new conditional weak table every time, it turns out // only way to clear ConditionalWeakTable is re-creating it. // also, conditional weak table has a leak - https://github.com/dotnet/coreclr/issues/665 _projectCompilationsWithAnalyzers = new ConditionalWeakTable<Project, CompilationWithAnalyzers?>(); } [Conditional("DEBUG")] private static void AssertAnalyzers(CompilationWithAnalyzers? compilation, IEnumerable<StateSet> stateSets) { if (compilation == null) { // this can happen if project doesn't support compilation or no stateSets are given. return; } // make sure analyzers are same. Contract.ThrowIfFalse(compilation.Analyzers.SetEquals(stateSets.Select(s => s.Analyzer).Where(a => !a.IsWorkspaceDiagnosticAnalyzer()))); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/DiagnosticsWindow.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Windows.Controls; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; using Roslyn.Hosting.Diagnostics.PerfMargin; using Roslyn.VisualStudio.DiagnosticsWindow.Telemetry; namespace Roslyn.VisualStudio.DiagnosticsWindow { [Guid("b2da68d7-fd1c-491a-a9a0-24f597b9f56c")] public class DiagnosticsWindow : ToolWindowPane { /// <summary> /// Standard constructor for the tool window. /// </summary> public DiagnosticsWindow(object _) : base(null) { // Set the window title reading it from the resources. Caption = Resources.ToolWindowTitle; // Set the image that will appear on the tab of the window frame // when docked with an other window // The resource ID correspond to the one defined in the resx file // while the Index is the offset in the bitmap strip. Each image in // the strip being 16x16. BitmapResourceID = 301; BitmapIndex = 1; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. var perfMarginPanel = new TabItem() { Header = "Perf", Content = new PerfMarginPanel() }; var telemetryPanel = new TabItem() { Header = "Telemetry", Content = new TelemetryPanel() }; var tabControl = new TabControl { TabStripPlacement = Dock.Bottom }; tabControl.Items.Add(perfMarginPanel); tabControl.Items.Add(telemetryPanel); base.Content = tabControl; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; using System.Windows.Controls; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell; using Roslyn.Hosting.Diagnostics.PerfMargin; using Roslyn.VisualStudio.DiagnosticsWindow.Telemetry; namespace Roslyn.VisualStudio.DiagnosticsWindow { [Guid("b2da68d7-fd1c-491a-a9a0-24f597b9f56c")] public class DiagnosticsWindow : ToolWindowPane { /// <summary> /// Standard constructor for the tool window. /// </summary> public DiagnosticsWindow(object _) : base(null) { // Set the window title reading it from the resources. Caption = Resources.ToolWindowTitle; // Set the image that will appear on the tab of the window frame // when docked with an other window // The resource ID correspond to the one defined in the resx file // while the Index is the offset in the bitmap strip. Each image in // the strip being 16x16. BitmapResourceID = 301; BitmapIndex = 1; // This is the user control hosted by the tool window; Note that, even if this class implements IDisposable, // we are not calling Dispose on this object. This is because ToolWindowPane calls Dispose on // the object returned by the Content property. var perfMarginPanel = new TabItem() { Header = "Perf", Content = new PerfMarginPanel() }; var telemetryPanel = new TabItem() { Header = "Telemetry", Content = new TelemetryPanel() }; var tabControl = new TabControl { TabStripPlacement = Dock.Bottom }; tabControl.Items.Add(perfMarginPanel); tabControl.Items.Add(telemetryPanel); base.Content = tabControl; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/ObjectPools/PooledHashSet.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.PooledObjects { internal partial class PooledHashSet<T> : IPooled, IReadOnlySet<T> { public static PooledDisposer<PooledHashSet<T>> GetInstance(out PooledHashSet<T> instance) { instance = GetInstance(); return new PooledDisposer<PooledHashSet<T>>(instance); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PooledObjects { internal partial class PooledHashSet<T> : IPooled, IReadOnlySet<T> { public static PooledDisposer<PooledHashSet<T>> GetInstance(out PooledHashSet<T> instance) { instance = GetInstance(); return new PooledDisposer<PooledHashSet<T>>(instance); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/ReferenceHighlighting/Tags/WrittenReferenceHighlightTag.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Tagging; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal class WrittenReferenceHighlightTag : NavigableHighlightTag { internal const string TagId = "MarkerFormatDefinition/HighlightedWrittenReference"; public static readonly WrittenReferenceHighlightTag Instance = new(); private WrittenReferenceHighlightTag() : base(TagId) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Tagging; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { internal class WrittenReferenceHighlightTag : NavigableHighlightTag { internal const string TagId = "MarkerFormatDefinition/HighlightedWrittenReference"; public static readonly WrittenReferenceHighlightTag Instance = new(); private WrittenReferenceHighlightTag() : base(TagId) { } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxListExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxListExtensions { public static SyntaxList<T> RemoveRange<T>(this SyntaxList<T> syntaxList, int index, int count) where T : SyntaxNode { var result = new List<T>(syntaxList); result.RemoveRange(index, count); return SyntaxFactory.List(result); } public static SyntaxList<T> ToSyntaxList<T>(this IEnumerable<T> sequence) where T : SyntaxNode => SyntaxFactory.List(sequence); public static SyntaxList<T> Insert<T>(this SyntaxList<T> list, int index, T item) where T : SyntaxNode => list.Take(index).Concat(item).Concat(list.Skip(index)).ToSyntaxList(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxListExtensions { public static SyntaxList<T> RemoveRange<T>(this SyntaxList<T> syntaxList, int index, int count) where T : SyntaxNode { var result = new List<T>(syntaxList); result.RemoveRange(index, count); return SyntaxFactory.List(result); } public static SyntaxList<T> ToSyntaxList<T>(this IEnumerable<T> sequence) where T : SyntaxNode => SyntaxFactory.List(sequence); public static SyntaxList<T> Insert<T>(this SyntaxList<T> list, int index, T item) where T : SyntaxNode => list.Take(index).Concat(item).Concat(list.Skip(index)).ToSyntaxList(); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ManagedKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ManagedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ManagedKeywordRecommender() : base(SyntaxKind.ManagedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsFunctionPointerCallingConventionContext(context.TargetToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ManagedKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ManagedKeywordRecommender() : base(SyntaxKind.ManagedKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.SyntaxTree.IsFunctionPointerCallingConventionContext(context.TargetToken); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, EditAndContinueTestHelpers.Net5RuntimeCapabilities, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.GetTestAccessor().SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); debuggingSession.RestartEditSession(inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, EditAndContinueTestHelpers.Net5RuntimeCapabilities, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.GetTestAccessor().SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); debuggingSession.RestartEditSession(inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = 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; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Host { /// <remarks> /// Instances of <see cref="IPersistentStorage"/> support both synchronous and asynchronous disposal. Asynchronous /// disposal should always be preferred as the implementation of synchronous disposal may end up blocking the caller /// on async work. /// </remarks> public interface IPersistentStorage : IDisposable, IAsyncDisposable { Task<Stream?> ReadStreamAsync(string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken = default); Task<Stream?> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken = default); /// <summary> /// Returns <see langword="true"/> if the data was successfully persisted to the storage subsystem. Subsequent /// calls to read the same keys should succeed if called within the same session. /// </summary> Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/PEWriter/DebugSourceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Immutable; namespace Microsoft.Cci { /// <summary> /// Represents the portion of a <see cref="DebugSourceDocument"/> that are derived /// from the source document content, and which can be computed asynchronously. /// </summary> internal struct DebugSourceInfo { /// <summary> /// The ID of the hash algorithm used. /// </summary> public readonly Guid ChecksumAlgorithmId; /// <summary> /// The hash of the document content. /// </summary> public readonly ImmutableArray<byte> Checksum; /// <summary> /// The source text to embed in the PDB. (If any, otherwise default.) /// </summary> public readonly ImmutableArray<byte> EmbeddedTextBlob; public DebugSourceInfo( ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob = default) : this(checksum, SourceHashAlgorithms.GetAlgorithmGuid(checksumAlgorithm), embeddedTextBlob) { } public DebugSourceInfo( ImmutableArray<byte> checksum, Guid checksumAlgorithmId, ImmutableArray<byte> embeddedTextBlob = default) { ChecksumAlgorithmId = checksumAlgorithmId; Checksum = checksum; EmbeddedTextBlob = embeddedTextBlob; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Debugging; using Microsoft.CodeAnalysis.Text; using System; using System.Collections.Immutable; namespace Microsoft.Cci { /// <summary> /// Represents the portion of a <see cref="DebugSourceDocument"/> that are derived /// from the source document content, and which can be computed asynchronously. /// </summary> internal struct DebugSourceInfo { /// <summary> /// The ID of the hash algorithm used. /// </summary> public readonly Guid ChecksumAlgorithmId; /// <summary> /// The hash of the document content. /// </summary> public readonly ImmutableArray<byte> Checksum; /// <summary> /// The source text to embed in the PDB. (If any, otherwise default.) /// </summary> public readonly ImmutableArray<byte> EmbeddedTextBlob; public DebugSourceInfo( ImmutableArray<byte> checksum, SourceHashAlgorithm checksumAlgorithm, ImmutableArray<byte> embeddedTextBlob = default) : this(checksum, SourceHashAlgorithms.GetAlgorithmGuid(checksumAlgorithm), embeddedTextBlob) { } public DebugSourceInfo( ImmutableArray<byte> checksum, Guid checksumAlgorithmId, ImmutableArray<byte> embeddedTextBlob = default) { ChecksumAlgorithmId = checksumAlgorithmId; Checksum = checksum; EmbeddedTextBlob = embeddedTextBlob; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Diagnostics/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes.RemoveInKeyword; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveInKeyword { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveInKeyword)] public class RemoveInKeywordCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveInKeywordCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new RemoveInKeywordCodeFixProvider()); [Fact] public async Task TestRemoveInKeyword() { await TestInRegularAndScript1Async( @"class Class { void M(int i) { } void N(int i) { M(in [|i|]); } }", @"class Class { void M(int i) { } void N(int i) { M(i); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments1() { await TestInRegularAndScript1Async( @"class Class { void M(int i, string s) { } void N(int i, string s) { M(in [|i|], s); } }", @"class Class { void M(int i, string s) { } void N(int i, string s) { M(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments2() { await TestInRegularAndScript1Async( @"class Class { void M(int i, int j) { } void N(int i, int j) { M(in [|i|], in j); } }", @"class Class { void M(int i, int j) { } void N(int i, int j) { M(i, in j); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() { await TestInRegularAndScript1Async( @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, in [|s|]); } }", @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, s); } }"); } [Fact] public async Task TestDontRemoveInKeyword() { await TestMissingInRegularAndScriptAsync( @"class Class { void M(in int i) { } void N(int i) { M(in [|i|]); } }"); } [Theory] [InlineData("in [|i|]", "i")] [InlineData(" in [|i|]", " i")] [InlineData("/* start */in [|i|]", "/* start */i")] [InlineData("/* start */ in [|i|]", "/* start */ i")] [InlineData( "/* start */ in [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */in /* middle */ [|i|] /* end */", "/* start */i /* end */")] public async Task TestRemoveInKeywordWithTrivia(string original, string expected) { await TestInRegularAndScript1Async( $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({original}); }} }}", $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({expected}); }} }}"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument1() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(i, s); } void N3(int i, string s) { M1(i); M2(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument2() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(in i, s); } void N3(int i, string s) { M1(i); M2(in i, s); } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeFixes.RemoveInKeyword; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveInKeyword { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveInKeyword)] public class RemoveInKeywordCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveInKeywordCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new RemoveInKeywordCodeFixProvider()); [Fact] public async Task TestRemoveInKeyword() { await TestInRegularAndScript1Async( @"class Class { void M(int i) { } void N(int i) { M(in [|i|]); } }", @"class Class { void M(int i) { } void N(int i) { M(i); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments1() { await TestInRegularAndScript1Async( @"class Class { void M(int i, string s) { } void N(int i, string s) { M(in [|i|], s); } }", @"class Class { void M(int i, string s) { } void N(int i, string s) { M(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments2() { await TestInRegularAndScript1Async( @"class Class { void M(int i, int j) { } void N(int i, int j) { M(in [|i|], in j); } }", @"class Class { void M(int i, int j) { } void N(int i, int j) { M(i, in j); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() { await TestInRegularAndScript1Async( @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, in [|s|]); } }", @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, s); } }"); } [Fact] public async Task TestDontRemoveInKeyword() { await TestMissingInRegularAndScriptAsync( @"class Class { void M(in int i) { } void N(int i) { M(in [|i|]); } }"); } [Theory] [InlineData("in [|i|]", "i")] [InlineData(" in [|i|]", " i")] [InlineData("/* start */in [|i|]", "/* start */i")] [InlineData("/* start */ in [|i|]", "/* start */ i")] [InlineData( "/* start */ in [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */in /* middle */ [|i|] /* end */", "/* start */i /* end */")] public async Task TestRemoveInKeywordWithTrivia(string original, string expected) { await TestInRegularAndScript1Async( $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({original}); }} }}", $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({expected}); }} }}"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument1() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(i, s); } void N3(int i, string s) { M1(i); M2(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument2() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(in i, s); } void N3(int i, string s) { M1(i); M2(in i, s); } }"); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/LocationExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class LocationExtensions { public static SyntaxTree GetSourceTreeOrThrow(this Location location) { Contract.ThrowIfNull(location.SourceTree); return location.SourceTree; } public static SyntaxToken FindToken(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindToken(location.SourceSpan.Start); public static SyntaxNode FindNode(this Location location, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan); public static SyntaxNode FindNode(this Location location, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, getInnermostNodeForTie: getInnermostNodeForTie); public static SyntaxNode FindNode(this Location location, bool findInsideTrivia, bool getInnermostNodeForTie, CancellationToken cancellationToken) => location.GetSourceTreeOrThrow().GetRoot(cancellationToken).FindNode(location.SourceSpan, findInsideTrivia, getInnermostNodeForTie); public static bool IsVisibleSourceLocation(this Location loc) { if (!loc.IsInSource) { return false; } var tree = loc.SourceTree; return !(tree == null || tree.IsHiddenPosition(loc.SourceSpan.Start)); } public static bool IntersectsWith(this Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource && loc2.IsInSource); return loc1.SourceTree == loc2.SourceTree && loc1.SourceSpan.IntersectsWith(loc2.SourceSpan); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Text/ContentTypeNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Editor { internal static class ContentTypeNames { public const string CSharpContentType = "CSharp"; public const string CSharpSignatureHelpContentType = "CSharp Signature Help"; public const string RoslynContentType = "Roslyn Languages"; public const string VisualBasicContentType = "Basic"; public const string VisualBasicSignatureHelpContentType = "Basic Signature Help"; public const string XamlContentType = "XAML"; public const string JavaScriptContentTypeName = "JavaScript"; public const string TypeScriptContentTypeName = "TypeScript"; public const string FSharpContentType = "F#"; public const string FSharpSignatureHelpContentType = "F# Signature Help"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Editor { internal static class ContentTypeNames { public const string CSharpContentType = "CSharp"; public const string CSharpSignatureHelpContentType = "CSharp Signature Help"; public const string RoslynContentType = "Roslyn Languages"; public const string VisualBasicContentType = "Basic"; public const string VisualBasicSignatureHelpContentType = "Basic Signature Help"; public const string XamlContentType = "XAML"; public const string JavaScriptContentTypeName = "JavaScript"; public const string TypeScriptContentTypeName = "TypeScript"; public const string FSharpContentType = "F#"; public const string FSharpSignatureHelpContentType = "F# Signature Help"; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Editing/SyntaxGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// A language agnostic factory for creating syntax nodes. /// /// This API can be used to create language specific syntax nodes that are semantically /// similar between languages. /// /// The trees generated by this API will try to respect user preferences when /// possible. For example, generating <see cref="MemberAccessExpression(SyntaxNode, string)"/> /// will be done in a way such that "this." or "Me." will be simplified according to user /// preference if any <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)" /> /// overload is called. /// </summary> public abstract class SyntaxGenerator : ILanguageService { public static SyntaxRemoveOptions DefaultRemoveOptions = SyntaxRemoveOptions.KeepUnbalancedDirectives | SyntaxRemoveOptions.AddElasticMarker; internal abstract SyntaxTrivia CarriageReturnLineFeed { get; } internal abstract SyntaxTrivia ElasticCarriageReturnLineFeed { get; } internal abstract bool RequiresExplicitImplementationForInterfaceMembers { get; } internal ISyntaxFacts SyntaxFacts => SyntaxGeneratorInternal.SyntaxFacts; internal abstract SyntaxGeneratorInternal SyntaxGeneratorInternal { get; } internal abstract SyntaxTrivia Whitespace(string text); internal abstract SyntaxTrivia SingleLineComment(string text); internal abstract SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim); internal abstract SyntaxToken CreateInterpolatedStringEndToken(); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the specified language. /// </summary> public static SyntaxGenerator GetGenerator(Workspace workspace, string language) => workspace.Services.GetLanguageServices(language).GetService<SyntaxGenerator>(); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the document. /// </summary> public static SyntaxGenerator GetGenerator(Document document) => GetGenerator(document.Project); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the project. /// </summary> public static SyntaxGenerator GetGenerator(Project project) => project.LanguageServices.GetService<SyntaxGenerator>(); #region Declarations /// <summary> /// Returns the node if it is a declaration, the immediate enclosing declaration if one exists, or null. /// </summary> public SyntaxNode GetDeclaration(SyntaxNode node) { while (node != null) { if (GetDeclarationKind(node) != DeclarationKind.None) { return node; } else { node = node.Parent; } } return null; } /// <summary> /// Returns the enclosing declaration of the specified kind or null. /// </summary> public SyntaxNode GetDeclaration(SyntaxNode node, DeclarationKind kind) { while (node != null) { if (GetDeclarationKind(node) == kind) { return node; } else { node = node.Parent; } } return null; } /// <summary> /// Creates a field declaration. /// </summary> public abstract SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, SyntaxNode initializer = null); /// <summary> /// Creates a field declaration matching an existing field symbol. /// </summary> public SyntaxNode FieldDeclaration(IFieldSymbol field) { var initializer = field.HasConstantValue ? this.LiteralExpression(field.ConstantValue) : null; return FieldDeclaration(field, initializer); } /// <summary> /// Creates a field declaration matching an existing field symbol. /// </summary> public SyntaxNode FieldDeclaration(IFieldSymbol field, SyntaxNode initializer) { return FieldDeclaration( field.Name, TypeExpression(field.Type), field.DeclaredAccessibility, DeclarationModifiers.From(field), initializer); } //internal abstract SyntaxNode ObjectMemberInitializer(IEnumerable<SyntaxNode> fieldInitializers); //internal abstract SyntaxNode NamedFieldInitializer(SyntaxNode name, SyntaxNode value); //internal abstract SyntaxNode WithObjectCreationInitializer(SyntaxNode objectCreationExpression, SyntaxNode initializer); /// <summary> /// Creates a method declaration. /// </summary> public abstract SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters = null, IEnumerable<string> typeParameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Creates a method declaration matching an existing method symbol. /// </summary> public SyntaxNode MethodDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode> statements = null) => MethodDeclaration(method, method.Name, statements); internal SyntaxNode MethodDeclaration(IMethodSymbol method, string name, IEnumerable<SyntaxNode> statements = null) { var decl = MethodDeclaration( name, parameters: method.Parameters.Select(p => ParameterDeclaration(p)), returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType), accessibility: method.DeclaredAccessibility, modifiers: DeclarationModifiers.From(method), statements: statements); if (method.TypeParameters.Length > 0) { decl = this.WithTypeParametersAndConstraints(decl, method.TypeParameters); } if (method.ExplicitInterfaceImplementations.Length > 0) { decl = this.WithExplicitInterfaceImplementations(decl, ImmutableArray<ISymbol>.CastUp(method.ExplicitInterfaceImplementations)); } return decl; } /// <summary> /// Creates a method declaration. /// </summary> public virtual SyntaxNode OperatorDeclaration( OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { throw new NotImplementedException(); } /// <summary> /// Creates a method declaration matching an existing method symbol. /// </summary> public SyntaxNode OperatorDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode> statements = null) { if (method.MethodKind != MethodKind.UserDefinedOperator) { throw new ArgumentException("Method is not an operator."); } var decl = OperatorDeclaration( GetOperatorKind(method), parameters: method.Parameters.Select(p => ParameterDeclaration(p)), returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType), accessibility: method.DeclaredAccessibility, modifiers: DeclarationModifiers.From(method), statements: statements); return decl; } private static OperatorKind GetOperatorKind(IMethodSymbol method) => method.Name switch { WellKnownMemberNames.ImplicitConversionName => OperatorKind.ImplicitConversion, WellKnownMemberNames.ExplicitConversionName => OperatorKind.ExplicitConversion, WellKnownMemberNames.AdditionOperatorName => OperatorKind.Addition, WellKnownMemberNames.BitwiseAndOperatorName => OperatorKind.BitwiseAnd, WellKnownMemberNames.BitwiseOrOperatorName => OperatorKind.BitwiseOr, WellKnownMemberNames.DecrementOperatorName => OperatorKind.Decrement, WellKnownMemberNames.DivisionOperatorName => OperatorKind.Division, WellKnownMemberNames.EqualityOperatorName => OperatorKind.Equality, WellKnownMemberNames.ExclusiveOrOperatorName => OperatorKind.ExclusiveOr, WellKnownMemberNames.FalseOperatorName => OperatorKind.False, WellKnownMemberNames.GreaterThanOperatorName => OperatorKind.GreaterThan, WellKnownMemberNames.GreaterThanOrEqualOperatorName => OperatorKind.GreaterThanOrEqual, WellKnownMemberNames.IncrementOperatorName => OperatorKind.Increment, WellKnownMemberNames.InequalityOperatorName => OperatorKind.Inequality, WellKnownMemberNames.LeftShiftOperatorName => OperatorKind.LeftShift, WellKnownMemberNames.LessThanOperatorName => OperatorKind.LessThan, WellKnownMemberNames.LessThanOrEqualOperatorName => OperatorKind.LessThanOrEqual, WellKnownMemberNames.LogicalNotOperatorName => OperatorKind.LogicalNot, WellKnownMemberNames.ModulusOperatorName => OperatorKind.Modulus, WellKnownMemberNames.MultiplyOperatorName => OperatorKind.Multiply, WellKnownMemberNames.OnesComplementOperatorName => OperatorKind.OnesComplement, WellKnownMemberNames.RightShiftOperatorName => OperatorKind.RightShift, WellKnownMemberNames.SubtractionOperatorName => OperatorKind.Subtraction, WellKnownMemberNames.TrueOperatorName => OperatorKind.True, WellKnownMemberNames.UnaryNegationOperatorName => OperatorKind.UnaryNegation, WellKnownMemberNames.UnaryPlusOperatorName => OperatorKind.UnaryPlus, _ => throw new ArgumentException("Unknown operator kind."), }; /// <summary> /// Creates a parameter declaration. /// </summary> public abstract SyntaxNode ParameterDeclaration( string name, SyntaxNode type = null, SyntaxNode initializer = null, RefKind refKind = RefKind.None); /// <summary> /// Creates a parameter declaration matching an existing parameter symbol. /// </summary> public SyntaxNode ParameterDeclaration(IParameterSymbol symbol, SyntaxNode initializer = null) { return ParameterDeclaration( symbol.Name, TypeExpression(symbol.Type), initializer, symbol.RefKind); } /// <summary> /// Creates a property declaration. The property will have a <c>get</c> accessor if /// <see cref="DeclarationModifiers.IsWriteOnly"/> is <see langword="false"/> and will have /// a <c>set</c> accessor if <see cref="DeclarationModifiers.IsReadOnly"/> is <see /// langword="false"/>. /// </summary> /// <remarks> /// In C# there is a distinction between passing in <see langword="null"/> for <paramref /// name="getAccessorStatements"/> or <paramref name="setAccessorStatements"/> versus /// passing in an empty list. <see langword="null"/> will produce an auto-property-accessor /// (i.e. <c>get;</c>) whereas an empty list will produce an accessor with an empty block /// (i.e. <c>get { }</c>). /// </remarks> public abstract SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null); /// <summary> /// Creates a property declaration using an existing property symbol as a signature. /// </summary> public SyntaxNode PropertyDeclaration( IPropertySymbol property, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null) { return PropertyDeclaration( property.Name, TypeExpression(property.Type), property.DeclaredAccessibility, DeclarationModifiers.From(property), getAccessorStatements, setAccessorStatements); } public SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, params SyntaxNode[] accessorDeclarations) => WithAccessorDeclarations(declaration, (IEnumerable<SyntaxNode>)accessorDeclarations); public abstract SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations); public abstract SyntaxNode GetAccessorDeclaration( Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> statements = null); public abstract SyntaxNode SetAccessorDeclaration( Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Creates an indexer declaration. /// </summary> public abstract SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null); /// <summary> /// Creates an indexer declaration matching an existing indexer symbol. /// </summary> public SyntaxNode IndexerDeclaration( IPropertySymbol indexer, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null) { return IndexerDeclaration( indexer.Parameters.Select(p => this.ParameterDeclaration(p)), TypeExpression(indexer.Type), indexer.DeclaredAccessibility, DeclarationModifiers.From(indexer), getAccessorStatements, setAccessorStatements); } /// <summary> /// Creates a statement that adds the given handler to the given event. /// </summary> public abstract SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler); /// <summary> /// Creates a statement that removes the given handler from the given event. /// </summary> public abstract SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler); /// <summary> /// Creates an event declaration. /// </summary> public abstract SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default); /// <summary> /// Creates an event declaration from an existing event symbol /// </summary> public SyntaxNode EventDeclaration(IEventSymbol symbol) { return EventDeclaration( symbol.Name, TypeExpression(symbol.Type), symbol.DeclaredAccessibility, DeclarationModifiers.From(symbol)); } /// <summary> /// Creates a custom event declaration. /// </summary> public abstract SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> parameters = null, IEnumerable<SyntaxNode> addAccessorStatements = null, IEnumerable<SyntaxNode> removeAccessorStatements = null); /// <summary> /// Creates a custom event declaration from an existing event symbol. /// </summary> public SyntaxNode CustomEventDeclaration( IEventSymbol symbol, IEnumerable<SyntaxNode> addAccessorStatements = null, IEnumerable<SyntaxNode> removeAccessorStatements = null) { var invoke = symbol.Type.GetMembers("Invoke").FirstOrDefault(m => m.Kind == SymbolKind.Method) as IMethodSymbol; var parameters = invoke?.Parameters.Select(p => this.ParameterDeclaration(p)); return CustomEventDeclaration( symbol.Name, TypeExpression(symbol.Type), symbol.DeclaredAccessibility, DeclarationModifiers.From(symbol), parameters: parameters, addAccessorStatements: addAccessorStatements, removeAccessorStatements: removeAccessorStatements); } /// <summary> /// Creates a constructor declaration. /// </summary> public abstract SyntaxNode ConstructorDeclaration( string containingTypeName = null, IEnumerable<SyntaxNode> parameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> baseConstructorArguments = null, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Create a constructor declaration using /// </summary> public SyntaxNode ConstructorDeclaration( IMethodSymbol constructorMethod, IEnumerable<SyntaxNode> baseConstructorArguments = null, IEnumerable<SyntaxNode> statements = null) { return ConstructorDeclaration( constructorMethod.ContainingType != null ? constructorMethod.ContainingType.Name : "New", constructorMethod.Parameters.Select(p => ParameterDeclaration(p)), constructorMethod.DeclaredAccessibility, DeclarationModifiers.From(constructorMethod), baseConstructorArguments, statements); } /// <summary> /// Converts method, property and indexer declarations into public interface implementations. /// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.) /// </summary> public SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType) => this.AsPublicInterfaceImplementation(declaration, interfaceType, null); /// <summary> /// Converts method, property and indexer declarations into public interface implementations. /// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.) /// </summary> public abstract SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string interfaceMemberName); /// <summary> /// Converts method, property and indexer declarations into private interface implementations. /// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly). /// </summary> public SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType) => this.AsPrivateInterfaceImplementation(declaration, interfaceType, null); /// <summary> /// Converts method, property and indexer declarations into private interface implementations. /// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly). /// </summary> public abstract SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string interfaceMemberName); /// <summary> /// Creates a class declaration. /// </summary> public abstract SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, SyntaxNode baseType = null, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates a struct declaration. /// </summary> public abstract SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates a interface declaration. /// </summary> public abstract SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum declaration. /// </summary> public abstract SyntaxNode EnumDeclaration( string name, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum declaration /// </summary> internal abstract SyntaxNode EnumDeclaration( string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum member /// </summary> public abstract SyntaxNode EnumMember(string name, SyntaxNode expression = null); /// <summary> /// Creates a delegate declaration. /// </summary> public abstract SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters = null, IEnumerable<string> typeParameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default); /// <summary> /// Creates a declaration matching an existing symbol. /// </summary> public SyntaxNode Declaration(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: return FieldDeclaration((IFieldSymbol)symbol); case SymbolKind.Property: var property = (IPropertySymbol)symbol; if (property.IsIndexer) { return IndexerDeclaration(property); } else { return PropertyDeclaration(property); } case SymbolKind.Event: var ev = (IEventSymbol)symbol; return EventDeclaration(ev); case SymbolKind.Method: var method = (IMethodSymbol)symbol; switch (method.MethodKind) { case MethodKind.Constructor: case MethodKind.SharedConstructor: return ConstructorDeclaration(method); case MethodKind.Ordinary: return MethodDeclaration(method); case MethodKind.UserDefinedOperator: return OperatorDeclaration(method); } break; case SymbolKind.Parameter: return ParameterDeclaration((IParameterSymbol)symbol); case SymbolKind.NamedType: var type = (INamedTypeSymbol)symbol; SyntaxNode declaration = null; switch (type.TypeKind) { case TypeKind.Class: declaration = ClassDeclaration( type.Name, accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type), baseType: TypeExpression(type.BaseType), interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Struct: declaration = StructDeclaration( type.Name, accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type), interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Interface: declaration = InterfaceDeclaration( type.Name, accessibility: type.DeclaredAccessibility, interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Enum: declaration = EnumDeclaration( type.Name, type.EnumUnderlyingType?.SpecialType == SpecialType.System_Int32 ? null : TypeExpression(type.EnumUnderlyingType.SpecialType), accessibility: type.DeclaredAccessibility, members: type.GetMembers().Where(s => s.Kind == SymbolKind.Field).Select(m => Declaration(m))); break; case TypeKind.Delegate: var invoke = type.GetMembers("Invoke").First() as IMethodSymbol; declaration = DelegateDeclaration( type.Name, parameters: invoke.Parameters.Select(p => ParameterDeclaration(p)), returnType: TypeExpression(invoke.ReturnType), accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type)); break; } if (declaration != null) { return WithTypeParametersAndConstraints(declaration, type.TypeParameters); } break; } throw new ArgumentException("Symbol cannot be converted to a declaration"); } private static bool CanBeDeclared(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: case SymbolKind.Parameter: return true; case SymbolKind.Method: var method = (IMethodSymbol)symbol; switch (method.MethodKind) { case MethodKind.Constructor: case MethodKind.SharedConstructor: case MethodKind.Ordinary: return true; } break; case SymbolKind.NamedType: var type = (INamedTypeSymbol)symbol; switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: return true; } break; } return false; } private SyntaxNode WithTypeParametersAndConstraints(SyntaxNode declaration, ImmutableArray<ITypeParameterSymbol> typeParameters) { if (typeParameters.Length > 0) { declaration = WithTypeParameters(declaration, typeParameters.Select(tp => tp.Name)); foreach (var tp in typeParameters) { if (tp.HasConstructorConstraint || tp.HasReferenceTypeConstraint || tp.HasValueTypeConstraint || tp.ConstraintTypes.Length > 0) { declaration = this.WithTypeConstraint(declaration, tp.Name, kinds: (tp.HasConstructorConstraint ? SpecialTypeConstraintKind.Constructor : SpecialTypeConstraintKind.None) | (tp.HasReferenceTypeConstraint ? SpecialTypeConstraintKind.ReferenceType : SpecialTypeConstraintKind.None) | (tp.HasValueTypeConstraint ? SpecialTypeConstraintKind.ValueType : SpecialTypeConstraintKind.None), types: tp.ConstraintTypes.Select(t => TypeExpression(t))); } } } return declaration; } internal abstract SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations); /// <summary> /// Converts a declaration (method, class, etc) into a declaration with type parameters. /// </summary> public abstract SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameters); /// <summary> /// Converts a declaration (method, class, etc) into a declaration with type parameters. /// </summary> public SyntaxNode WithTypeParameters(SyntaxNode declaration, params string[] typeParameters) => WithTypeParameters(declaration, (IEnumerable<string>)typeParameters); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public abstract SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types = null); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, params SyntaxNode[] types) => WithTypeConstraint(declaration, typeParameterName, kinds, (IEnumerable<SyntaxNode>)types); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, params SyntaxNode[] types) => WithTypeConstraint(declaration, typeParameterName, SpecialTypeConstraintKind.None, (IEnumerable<SyntaxNode>)types); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public abstract SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(SyntaxNode name, params SyntaxNode[] declarations) => NamespaceDeclaration(name, (IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(string name, IEnumerable<SyntaxNode> declarations) => NamespaceDeclaration(DottedName(name), declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(string name, params SyntaxNode[] declarations) => NamespaceDeclaration(DottedName(name), (IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a compilation unit declaration /// </summary> /// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param> public abstract SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations); /// <summary> /// Creates a compilation unit declaration /// </summary> /// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param> public SyntaxNode CompilationUnit(params SyntaxNode[] declarations) => CompilationUnit((IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a namespace import declaration. /// </summary> /// <param name="name">The name of the namespace being imported.</param> public abstract SyntaxNode NamespaceImportDeclaration(SyntaxNode name); /// <summary> /// Creates a namespace import declaration. /// </summary> /// <param name="name">The name of the namespace being imported.</param> public SyntaxNode NamespaceImportDeclaration(string name) => NamespaceImportDeclaration(DottedName(name)); /// <summary> /// Creates an alias import declaration. /// </summary> /// <param name="aliasIdentifierName">The name of the alias.</param> /// <param name="symbol">The namespace or type to be aliased.</param> public SyntaxNode AliasImportDeclaration(string aliasIdentifierName, INamespaceOrTypeSymbol symbol) => AliasImportDeclaration(aliasIdentifierName, NameExpression(symbol)); /// <summary> /// Creates an alias import declaration. /// </summary> /// <param name="aliasIdentifierName">The name of the alias.</param> /// <param name="name">The namespace or type to be aliased.</param> public abstract SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name); /// <summary> /// Creates an attribute. /// </summary> public abstract SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments = null); /// <summary> /// Creates an attribute. /// </summary> public SyntaxNode Attribute(string name, IEnumerable<SyntaxNode> attributeArguments = null) => Attribute(DottedName(name), attributeArguments); /// <summary> /// Creates an attribute. /// </summary> public SyntaxNode Attribute(string name, params SyntaxNode[] attributeArguments) => Attribute(name, (IEnumerable<SyntaxNode>)attributeArguments); /// <summary> /// Creates an attribute matching existing attribute data. /// </summary> public SyntaxNode Attribute(AttributeData attribute) { var args = attribute.ConstructorArguments.Select(a => this.AttributeArgument(this.TypedConstantExpression(a))) .Concat(attribute.NamedArguments.Select(n => this.AttributeArgument(n.Key, this.TypedConstantExpression(n.Value)))) .ToBoxedImmutableArray(); return Attribute( name: this.TypeExpression(attribute.AttributeClass), attributeArguments: args.Count > 0 ? args : null); } /// <summary> /// Creates an attribute argument. /// </summary> public abstract SyntaxNode AttributeArgument(string name, SyntaxNode expression); /// <summary> /// Creates an attribute argument. /// </summary> public SyntaxNode AttributeArgument(SyntaxNode expression) => AttributeArgument(null, expression); /// <summary> /// Removes all attributes from the declaration, including return attributes. /// </summary> public SyntaxNode RemoveAllAttributes(SyntaxNode declaration) => this.RemoveNodes(declaration, this.GetAttributes(declaration).Concat(this.GetReturnAttributes(declaration))); /// <summary> /// Removes comments from leading and trailing trivia, as well /// as potentially removing comments from opening and closing tokens. /// </summary> internal abstract SyntaxNode RemoveAllComments(SyntaxNode node); internal SyntaxNode RemoveLeadingAndTrailingComments(SyntaxNode node) { return node.WithLeadingTrivia(RemoveCommentLines(node.GetLeadingTrivia())) .WithTrailingTrivia(RemoveCommentLines(node.GetTrailingTrivia())); } internal SyntaxToken RemoveLeadingAndTrailingComments(SyntaxToken token) { return token.WithLeadingTrivia(RemoveCommentLines(token.LeadingTrivia)) .WithTrailingTrivia(RemoveCommentLines(token.TrailingTrivia)); } internal abstract SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList); internal abstract bool IsRegularOrDocComment(SyntaxTrivia trivia); internal SyntaxNode RemoveAllTypeInheritance(SyntaxNode declaration) => this.RemoveNodes(declaration, this.GetTypeInheritance(declaration)); internal abstract ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration); /// <summary> /// Gets the attributes of a declaration, not including the return attributes. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the attributes inserted. /// </summary> public abstract SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes); /// <summary> /// Creates a new instance of the declaration with the attributes inserted. /// </summary> public SyntaxNode InsertAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes) => this.InsertAttributes(declaration, index, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Creates a new instance of a declaration with the specified attributes added. /// </summary> public SyntaxNode AddAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes) => this.InsertAttributes(declaration, this.GetAttributes(declaration).Count, attributes); /// <summary> /// Creates a new instance of a declaration with the specified attributes added. /// </summary> public SyntaxNode AddAttributes(SyntaxNode declaration, params SyntaxNode[] attributes) => AddAttributes(declaration, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Gets the return attributes from the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration); /// <summary> /// Creates a new instance of a method declaration with return attributes inserted. /// </summary> public abstract SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes); /// <summary> /// Creates a new instance of a method declaration with return attributes inserted. /// </summary> public SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes) => this.InsertReturnAttributes(declaration, index, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Creates a new instance of a method declaration with return attributes added. /// </summary> public SyntaxNode AddReturnAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes) => this.InsertReturnAttributes(declaration, this.GetReturnAttributes(declaration).Count, attributes); /// <summary> /// Creates a new instance of a method declaration node with return attributes added. /// </summary> public SyntaxNode AddReturnAttributes(SyntaxNode declaration, params SyntaxNode[] attributes) => AddReturnAttributes(declaration, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Gets the attribute arguments for the attribute declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration); /// <summary> /// Creates a new instance of the attribute with the arguments inserted. /// </summary> public abstract SyntaxNode InsertAttributeArguments(SyntaxNode attributeDeclaration, int index, IEnumerable<SyntaxNode> attributeArguments); /// <summary> /// Creates a new instance of the attribute with the arguments added. /// </summary> public SyntaxNode AddAttributeArguments(SyntaxNode attributeDeclaration, IEnumerable<SyntaxNode> attributeArguments) => this.InsertAttributeArguments(attributeDeclaration, this.GetAttributeArguments(attributeDeclaration).Count, attributeArguments); /// <summary> /// Gets the namespace imports that are part of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the namespace imports inserted. /// </summary> public abstract SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports inserted. /// </summary> public SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, params SyntaxNode[] imports) => this.InsertNamespaceImports(declaration, index, (IEnumerable<SyntaxNode>)imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports added. /// </summary> public SyntaxNode AddNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports) => this.InsertNamespaceImports(declaration, this.GetNamespaceImports(declaration).Count, imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports added. /// </summary> public SyntaxNode AddNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports) => this.AddNamespaceImports(declaration, (IEnumerable<SyntaxNode>)imports); /// <summary> /// Gets the current members of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the members inserted. /// </summary> public abstract SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members); /// <summary> /// Creates a new instance of the declaration with the members inserted. /// </summary> public SyntaxNode InsertMembers(SyntaxNode declaration, int index, params SyntaxNode[] members) => this.InsertMembers(declaration, index, (IEnumerable<SyntaxNode>)members); /// <summary> /// Creates a new instance of the declaration with the members added to the end. /// </summary> public SyntaxNode AddMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => this.InsertMembers(declaration, this.GetMembers(declaration).Count, members); /// <summary> /// Creates a new instance of the declaration with the members added to the end. /// </summary> public SyntaxNode AddMembers(SyntaxNode declaration, params SyntaxNode[] members) => this.AddMembers(declaration, (IEnumerable<SyntaxNode>)members); /// <summary> /// Gets the accessibility of the declaration. /// </summary> public abstract Accessibility GetAccessibility(SyntaxNode declaration); /// <summary> /// Changes the accessibility of the declaration. /// </summary> public abstract SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility); /// <summary> /// Gets the <see cref="DeclarationModifiers"/> for the declaration. /// </summary> public abstract DeclarationModifiers GetModifiers(SyntaxNode declaration); /// <summary> /// Changes the <see cref="DeclarationModifiers"/> for the declaration. /// </summary> public abstract SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> public abstract DeclarationKind GetDeclarationKind(SyntaxNode declaration); /// <summary> /// Gets the name of the declaration. /// </summary> public abstract string GetName(SyntaxNode declaration); /// <summary> /// Changes the name of the declaration. /// </summary> public abstract SyntaxNode WithName(SyntaxNode declaration, string name); /// <summary> /// Gets the type of the declaration. /// </summary> public abstract SyntaxNode GetType(SyntaxNode declaration); /// <summary> /// Changes the type of the declaration. /// </summary> public abstract SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type); /// <summary> /// Gets the list of parameters for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration); internal abstract SyntaxNode GetParameterListNode(SyntaxNode declaration); /// <summary> /// Inserts the parameters at the specified index into the declaration. /// </summary> public abstract SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters); /// <summary> /// Adds the parameters to the declaration. /// </summary> public SyntaxNode AddParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters) => this.InsertParameters(declaration, this.GetParameters(declaration).Count, parameters); /// <summary> /// Gets the list of switch sections for the statement. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement); /// <summary> /// Inserts the switch sections at the specified index into the statement. /// </summary> public abstract SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections); /// <summary> /// Adds the switch sections to the statement. /// </summary> public SyntaxNode AddSwitchSections(SyntaxNode switchStatement, IEnumerable<SyntaxNode> switchSections) => this.InsertSwitchSections(switchStatement, this.GetSwitchSections(switchStatement).Count, switchSections); /// <summary> /// Gets the expression associated with the declaration. /// </summary> public abstract SyntaxNode GetExpression(SyntaxNode declaration); /// <summary> /// Changes the expression associated with the declaration. /// </summary> public abstract SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression); /// <summary> /// Gets the statements for the body of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the declaration. /// </summary> public abstract SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets the accessors for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration); /// <summary> /// Gets the accessor of the specified kind for the declaration. /// </summary> public SyntaxNode GetAccessor(SyntaxNode declaration, DeclarationKind kind) => this.GetAccessors(declaration).FirstOrDefault(a => GetDeclarationKind(a) == kind); /// <summary> /// Creates a new instance of the declaration with the accessors inserted. /// </summary> public abstract SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors); /// <summary> /// Creates a new instance of the declaration with the accessors added. /// </summary> public SyntaxNode AddAccessors(SyntaxNode declaration, IEnumerable<SyntaxNode> accessors) => this.InsertAccessors(declaration, this.GetAccessors(declaration).Count, accessors); /// <summary> /// Gets the statements for the body of the get-accessor of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the get-accessor of the declaration. /// </summary> public abstract SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets the statements for the body of the set-accessor of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the set-accessor of the declaration. /// </summary> public abstract SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets a list of the base and interface types for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration); /// <summary> /// Adds a base type to the declaration /// </summary> public abstract SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType); /// <summary> /// Adds an interface type to the declaration /// </summary> public abstract SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType); internal abstract SyntaxNode AsInterfaceMember(SyntaxNode member); #endregion #region Remove, Replace, Insert /// <summary> /// Replaces the node in the root's tree with the new node. /// </summary> public virtual SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode node, SyntaxNode newDeclaration) { if (newDeclaration != null) { return root.ReplaceNode(node, newDeclaration); } else { return this.RemoveNode(root, node); } } internal static SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.ReplaceNode(node, newDeclarations); /// <summary> /// Inserts the new node before the specified declaration. /// </summary> public virtual SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.InsertNodesBefore(node, newDeclarations); /// <summary> /// Inserts the new node before the specified declaration. /// </summary> public virtual SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.InsertNodesAfter(node, newDeclarations); /// <summary> /// Removes the node from the sub tree starting at the root. /// </summary> public virtual SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => RemoveNode(root, node, DefaultRemoveOptions); /// <summary> /// Removes the node from the sub tree starting at the root. /// </summary> public virtual SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) => root.RemoveNode(node, options); /// <summary> /// Removes all the declarations from the sub tree starting at the root. /// </summary> public SyntaxNode RemoveNodes(SyntaxNode root, IEnumerable<SyntaxNode> declarations) { var newRoot = root.TrackNodes(declarations); foreach (var decl in declarations) { newRoot = this.RemoveNode(newRoot, newRoot.GetCurrentNode(decl)); } return newRoot; } #endregion #region Utility internal abstract SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) where TElement : SyntaxNode; internal abstract SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) where TElement : SyntaxNode; internal static SyntaxTokenList Merge(SyntaxTokenList original, SyntaxTokenList newList) { // return tokens from newList, but use original tokens of kind matches return new SyntaxTokenList(newList.Select( token => Any(original, token.RawKind) ? original.First(tk => tk.RawKind == token.RawKind) : token)); } private static bool Any(SyntaxTokenList original, int rawKind) { foreach (var token in original) { if (token.RawKind == rawKind) { return true; } } return false; } protected static SyntaxNode PreserveTrivia<TNode>(TNode node, Func<TNode, SyntaxNode> nodeChanger) where TNode : SyntaxNode { if (node == null) { return node; } var nodeWithoutTrivia = node.WithoutLeadingTrivia().WithoutTrailingTrivia(); var changedNode = nodeChanger(nodeWithoutTrivia); if (changedNode == nodeWithoutTrivia) { return node; } else { return changedNode .WithLeadingTrivia(node.GetLeadingTrivia().Concat(changedNode.GetLeadingTrivia())) .WithTrailingTrivia(changedNode.GetTrailingTrivia().Concat(node.GetTrailingTrivia())); } } protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxNode original, SyntaxNode replacement) { var combinedTriviaReplacement = replacement.WithLeadingTrivia(original.GetLeadingTrivia().AddRange(replacement.GetLeadingTrivia())) .WithTrailingTrivia(replacement.GetTrailingTrivia().AddRange(original.GetTrailingTrivia())); return root.ReplaceNode(original, combinedTriviaReplacement); } protected static SyntaxNode ReplaceWithTrivia<TNode>(SyntaxNode root, TNode original, Func<TNode, SyntaxNode> replacer) where TNode : SyntaxNode { return ReplaceWithTrivia(root, original, replacer(original)); } protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxToken original, SyntaxToken replacement) { var combinedTriviaReplacement = replacement.WithLeadingTrivia(original.LeadingTrivia.AddRange(replacement.LeadingTrivia)) .WithTrailingTrivia(replacement.TrailingTrivia.AddRange(original.TrailingTrivia)); return root.ReplaceToken(original, combinedTriviaReplacement); } /// <summary> /// Creates a new instance of the node with the leading and trailing trivia removed and replaced with elastic markers. /// </summary> public abstract TNode ClearTrivia<TNode>(TNode node) where TNode : SyntaxNode; #pragma warning disable CA1822 // Mark members as static - shipped public API protected int IndexOf<T>(IReadOnlyList<T> list, T element) #pragma warning restore CA1822 // Mark members as static { for (int i = 0, count = list.Count; i < count; i++) { if (EqualityComparer<T>.Default.Equals(list[i], element)) { return i; } } return -1; } protected static SyntaxNode ReplaceRange(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> replacements) { var first = replacements.First(); var trackedFirst = first.TrackNodes(first); var newRoot = root.ReplaceNode(node, trackedFirst); var currentFirst = newRoot.GetCurrentNode(first); return newRoot.InsertNodesAfter(currentFirst, replacements.Skip(1)); } protected static SeparatedSyntaxList<TNode> RemoveRange<TNode>(SeparatedSyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { for (; count > 0 && offset < list.Count; count--) { list = list.RemoveAt(offset); } return list; } protected static SyntaxList<TNode> RemoveRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { for (; count > 0 && offset < list.Count; count--) { list = list.RemoveAt(offset); } return list; } #endregion #region Statements /// <summary> /// Creates statement that allows an expression to execute in a statement context. /// This is typically an invocation or assignment expression. /// </summary> /// <param name="expression">The expression that is to be executed. This is usually a method invocation expression.</param> public abstract SyntaxNode ExpressionStatement(SyntaxNode expression); /// <summary> /// Creates a statement that can be used to return a value from a method body. /// </summary> /// <param name="expression">An optional expression that can be returned.</param> public abstract SyntaxNode ReturnStatement(SyntaxNode expression = null); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal SyntaxNode YieldReturnStatement(SyntaxNode expression) => SyntaxGeneratorInternal.YieldReturnStatement(expression); /// <summary> /// Creates a statement that can be used to throw an exception. /// </summary> /// <param name="expression">An optional expression that can be thrown.</param> public abstract SyntaxNode ThrowStatement(SyntaxNode expression = null); /// <summary> /// Creates an expression that can be used to throw an exception. /// </summary> public abstract SyntaxNode ThrowExpression(SyntaxNode expression); /// <summary> /// True if <see cref="ThrowExpression"/> can be used /// </summary> internal abstract bool SupportsThrowExpression(); /// <summary> /// <see langword="true"/> if the language requires a <see cref="TypeExpression(ITypeSymbol)"/> /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(ITypeSymbol, string, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal bool RequiresLocalDeclarationType() => SyntaxGeneratorInternal.RequiresLocalDeclarationType(); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, string identifier, SyntaxNode initializer = null, bool isConst = false); internal SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false) => SyntaxGeneratorInternal.LocalDeclarationStatement(type, identifier, initializer, isConst); internal SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer) => SyntaxGeneratorInternal.WithInitializer(variableDeclarator, initializer); internal SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value) => SyntaxGeneratorInternal.EqualsValueClause(operatorToken, value); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public SyntaxNode LocalDeclarationStatement( ITypeSymbol type, string name, SyntaxNode initializer = null, bool isConst = false) => LocalDeclarationStatement(TypeExpression(type), name, initializer, isConst); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public SyntaxNode LocalDeclarationStatement(string name, SyntaxNode initializer) => LocalDeclarationStatement((SyntaxNode)null, name, initializer); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement((SyntaxNode)null, name, initializer); /// <summary> /// Creates an if-statement /// </summary> /// <param name="condition">A condition expression.</param> /// <param name="trueStatements">The statements that are executed if the condition is true.</param> /// <param name="falseStatements">The statements that are executed if the condition is false.</param> public abstract SyntaxNode IfStatement( SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null); /// <summary> /// Creates an if statement /// </summary> /// <param name="condition">A condition expression.</param> /// <param name="trueStatements">The statements that are executed if the condition is true.</param> /// <param name="falseStatement">A single statement that is executed if the condition is false.</param> public SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, SyntaxNode falseStatement) => IfStatement(condition, trueStatements, new[] { falseStatement }); /// <summary> /// Creates a switch statement that branches to individual sections based on the value of the specified expression. /// </summary> public abstract SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> sections); /// <summary> /// Creates a switch statement that branches to individual sections based on the value of the specified expression. /// </summary> public SyntaxNode SwitchStatement(SyntaxNode expression, params SyntaxNode[] sections) => SwitchStatement(expression, (IEnumerable<SyntaxNode>)sections); /// <summary> /// Creates a section for a switch statement. /// </summary> public abstract SyntaxNode SwitchSection(IEnumerable<SyntaxNode> caseExpressions, IEnumerable<SyntaxNode> statements); internal abstract SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a single-case section a switch statement. /// </summary> public SyntaxNode SwitchSection(SyntaxNode caseExpression, IEnumerable<SyntaxNode> statements) => SwitchSection(new[] { caseExpression }, statements); /// <summary> /// Creates a default section for a switch statement. /// </summary> public abstract SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements); /// <summary> /// Create a statement that exits a switch statement and continues after it. /// </summary> public abstract SyntaxNode ExitSwitchStatement(); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public abstract SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public SyntaxNode UsingStatement(string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) => UsingStatement(null, name, expression, statements); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public abstract SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a statement that represents a lock-block pattern. /// </summary> public abstract SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a try-catch or try-catch-finally statement. /// </summary> public abstract SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null); /// <summary> /// Creates a try-catch or try-catch-finally statement. /// </summary> public SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, params SyntaxNode[] catchClauses) => TryCatchStatement(tryStatements, (IEnumerable<SyntaxNode>)catchClauses); /// <summary> /// Creates a try-finally statement. /// </summary> public SyntaxNode TryFinallyStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> finallyStatements) => TryCatchStatement(tryStatements, catchClauses: null, finallyStatements: finallyStatements); /// <summary> /// Creates a catch-clause. /// </summary> public abstract SyntaxNode CatchClause(SyntaxNode type, string identifier, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a catch-clause. /// </summary> public SyntaxNode CatchClause(ITypeSymbol type, string identifier, IEnumerable<SyntaxNode> statements) => CatchClause(TypeExpression(type), identifier, statements); /// <summary> /// Creates a while-loop statement /// </summary> public abstract SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a block of statements. Not supported in VB. /// </summary> internal abstract SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements); #endregion #region Expressions internal abstract SyntaxToken NumericLiteralToken(string text, ulong value); internal SyntaxToken InterpolatedStringTextToken(string content, string value) => SyntaxGeneratorInternal.InterpolatedStringTextToken(content, value); internal SyntaxNode InterpolatedStringText(SyntaxToken textToken) => SyntaxGeneratorInternal.InterpolatedStringText(textToken); internal SyntaxNode Interpolation(SyntaxNode syntaxNode) => SyntaxGeneratorInternal.Interpolation(syntaxNode); internal SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken) => SyntaxGeneratorInternal.InterpolatedStringExpression(startToken, content, endToken); internal SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment) => SyntaxGeneratorInternal.InterpolationAlignmentClause(alignment); internal SyntaxNode InterpolationFormatClause(string format) => SyntaxGeneratorInternal.InterpolationFormatClause(format); /// <summary> /// An expression that represents the default value of a type. /// This is typically a null value for reference types or a zero-filled value for value types. /// </summary> public abstract SyntaxNode DefaultExpression(SyntaxNode type); public abstract SyntaxNode DefaultExpression(ITypeSymbol type); /// <summary> /// Creates an expression that denotes the containing method's this-parameter. /// </summary> public abstract SyntaxNode ThisExpression(); /// <summary> /// Creates an expression that denotes the containing method's base-parameter. /// </summary> public abstract SyntaxNode BaseExpression(); /// <summary> /// Creates a literal expression. This is typically numeric primitives, strings or chars. /// </summary> public abstract SyntaxNode LiteralExpression(object value); /// <summary> /// Creates an expression for a typed constant. /// </summary> public abstract SyntaxNode TypedConstantExpression(TypedConstant value); /// <summary> /// Creates an expression that denotes the boolean false literal. /// </summary> public SyntaxNode FalseLiteralExpression() => LiteralExpression(false); /// <summary> /// Creates an expression that denotes the boolean true literal. /// </summary> public SyntaxNode TrueLiteralExpression() => LiteralExpression(true); /// <summary> /// Creates an expression that denotes the null literal. /// </summary> public SyntaxNode NullLiteralExpression() => LiteralExpression(null); /// <summary> /// Creates an expression that denotes a simple identifier name. /// </summary> /// <param name="identifier"></param> /// <returns></returns> public abstract SyntaxNode IdentifierName(string identifier); internal abstract SyntaxNode IdentifierName(SyntaxToken identifier); internal SyntaxToken Identifier(string identifier) => SyntaxGeneratorInternal.Identifier(identifier); internal abstract SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public abstract SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments); internal abstract SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, IEnumerable<ITypeSymbol> typeArguments) => GenericName(identifier, typeArguments.Select(ta => TypeExpression(ta))); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, params SyntaxNode[] typeArguments) => GenericName(identifier, (IEnumerable<SyntaxNode>)typeArguments); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, params ITypeSymbol[] typeArguments) => GenericName(identifier, (IEnumerable<ITypeSymbol>)typeArguments); /// <summary> /// Converts an expression that ends in a name into an expression that ends in a generic name. /// If the expression already ends in a generic name, the new type arguments are used instead. /// </summary> public abstract SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments); /// <summary> /// Converts an expression that ends in a name into an expression that ends in a generic name. /// If the expression already ends in a generic name, the new type arguments are used instead. /// </summary> public SyntaxNode WithTypeArguments(SyntaxNode expression, params SyntaxNode[] typeArguments) => WithTypeArguments(expression, (IEnumerable<SyntaxNode>)typeArguments); /// <summary> /// Creates a name expression that denotes a qualified name. /// The left operand can be any name expression. /// The right operand can be either and identifier or generic name. /// </summary> public abstract SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns a new name node qualified with the 'global' alias ('Global' in VB). /// </summary> internal abstract SyntaxNode GlobalAliasedName(SyntaxNode name); /// <summary> /// Creates a name expression from a dotted name string. /// </summary> public SyntaxNode DottedName(string dottedName) { if (dottedName == null) { throw new ArgumentNullException(nameof(dottedName)); } var parts = dottedName.Split(s_dotSeparator); SyntaxNode name = null; foreach (var part in parts) { if (name == null) { name = IdentifierName(part); } else { name = QualifiedName(name, IdentifierName(part)).WithAdditionalAnnotations(Simplification.Simplifier.Annotation); } } return name; } private static readonly char[] s_dotSeparator = new char[] { '.' }; /// <summary> /// Creates a name that denotes a type or namespace. /// </summary> /// <param name="namespaceOrTypeSymbol">The symbol to create a name for.</param> /// <returns></returns> public abstract SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol); /// <summary> /// Creates an expression that denotes a type. /// </summary> public abstract SyntaxNode TypeExpression(ITypeSymbol typeSymbol); /// <summary> /// Creates an expression that denotes a type. If addImport is false, /// adds a <see cref="DoNotAddImportsAnnotation"/> which will prevent any /// imports or usings from being added for the type. /// </summary> public SyntaxNode TypeExpression(ITypeSymbol typeSymbol, bool addImport) { var expression = TypeExpression(typeSymbol); return addImport ? expression : expression.WithAdditionalAnnotations(DoNotAddImportsAnnotation.Annotation); } /// <summary> /// Creates an expression that denotes a special type name. /// </summary> public abstract SyntaxNode TypeExpression(SpecialType specialType); /// <summary> /// Creates an expression that denotes an array type. /// </summary> public abstract SyntaxNode ArrayTypeExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes a nullable type. /// </summary> public abstract SyntaxNode NullableTypeExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(IEnumerable<SyntaxNode> elements) { if (elements == null) { throw new ArgumentNullException(nameof(elements)); } if (elements.Count() <= 1) { throw new ArgumentException("Tuples must have at least two elements.", nameof(elements)); } return CreateTupleType(elements); } internal abstract SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(params SyntaxNode[] elements) => TupleTypeExpression((IEnumerable<SyntaxNode>)elements); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(IEnumerable<ITypeSymbol> elementTypes, IEnumerable<string> elementNames = null) { if (elementTypes == null) { throw new ArgumentNullException(nameof(elementTypes)); } if (elementNames != null) { if (elementNames.Count() != elementTypes.Count()) { throw new ArgumentException("The number of element names must match the cardinality of the tuple.", nameof(elementNames)); } return TupleTypeExpression(elementTypes.Zip(elementNames, (type, name) => TupleElementExpression(type, name))); } return TupleTypeExpression(elementTypes.Select(type => TupleElementExpression(type, name: null))); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates an expression that denotes a tuple element. /// </summary> public abstract SyntaxNode TupleElementExpression(SyntaxNode type, string name = null); /// <summary> /// Creates an expression that denotes a tuple element. /// </summary> public SyntaxNode TupleElementExpression(ITypeSymbol type, string name = null) => TupleElementExpression(TypeExpression(type), name); #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates an expression that denotes an assignment from the right argument to left argument. /// </summary> public abstract SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a value-type equality test operation. /// </summary> public abstract SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a reference-type equality test operation. /// </summary> public abstract SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a value-type inequality test operation. /// </summary> public abstract SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a reference-type inequality test operation. /// </summary> public abstract SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a less-than test operation. /// </summary> public abstract SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a less-than-or-equal test operation. /// </summary> public abstract SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a greater-than test operation. /// </summary> public abstract SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a greater-than-or-equal test operation. /// </summary> public abstract SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a unary negation operation. /// </summary> public abstract SyntaxNode NegateExpression(SyntaxNode expression); /// <summary> /// Creates an expression that denotes an addition operation. /// </summary> public abstract SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes an subtraction operation. /// </summary> public abstract SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a multiplication operation. /// </summary> public abstract SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a division operation. /// </summary> public abstract SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a modulo operation. /// </summary> public abstract SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-and operation. /// </summary> public abstract SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-or operation. /// </summary> public abstract SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-not operation /// </summary> public abstract SyntaxNode BitwiseNotExpression(SyntaxNode operand); /// <summary> /// Creates an expression that denotes a logical-and operation. /// </summary> public abstract SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a logical-or operation. /// </summary> public abstract SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a logical not operation. /// </summary> public abstract SyntaxNode LogicalNotExpression(SyntaxNode expression); /// <summary> /// Creates an expression that denotes a conditional evaluation operation. /// </summary> public abstract SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse); /// <summary> /// Creates an expression that denotes a conditional access operation. Use <see /// cref="MemberBindingExpression"/> and <see /// cref="ElementBindingExpression(IEnumerable{SyntaxNode})"/> to generate the <paramref /// name="whenNotNull"/> argument. /// </summary> public abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); /// <summary> /// Creates an expression that denotes a member binding operation. /// </summary> public abstract SyntaxNode MemberBindingExpression(SyntaxNode name); /// <summary> /// Creates an expression that denotes an element binding operation. /// </summary> public abstract SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates an expression that denotes an element binding operation. /// </summary> public SyntaxNode ElementBindingExpression(params SyntaxNode[] arguments) => ElementBindingExpression((IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an expression that denotes a coalesce operation. /// </summary> public abstract SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates a member access expression. /// </summary> public virtual SyntaxNode MemberAccessExpression(SyntaxNode expression, SyntaxNode memberName) { return MemberAccessExpressionWorker(expression, memberName) .WithAdditionalAnnotations(Simplification.Simplifier.Annotation); } internal abstract SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode memberName); internal SyntaxNode RefExpression(SyntaxNode expression) => SyntaxGeneratorInternal.RefExpression(expression); /// <summary> /// Creates a member access expression. /// </summary> public SyntaxNode MemberAccessExpression(SyntaxNode expression, string memberName) => MemberAccessExpression(expression, IdentifierName(memberName)); /// <summary> /// Creates an array creation expression for a single dimensional array of specified size. /// </summary> public abstract SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size); /// <summary> /// Creates an array creation expression for a single dimensional array with specified initial element values. /// </summary> public abstract SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements); /// <summary> /// Creates an object creation expression. /// </summary> public abstract SyntaxNode ObjectCreationExpression(SyntaxNode namedType, IEnumerable<SyntaxNode> arguments); internal abstract SyntaxNode ObjectCreationExpression( SyntaxNode namedType, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(ITypeSymbol type, IEnumerable<SyntaxNode> arguments) => ObjectCreationExpression(TypeExpression(type), arguments); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(SyntaxNode type, params SyntaxNode[] arguments) => ObjectCreationExpression(type, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(ITypeSymbol type, params SyntaxNode[] arguments) => ObjectCreationExpression(type, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates a invocation expression. /// </summary> public abstract SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates a invocation expression /// </summary> public SyntaxNode InvocationExpression(SyntaxNode expression, params SyntaxNode[] arguments) => InvocationExpression(expression, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public abstract SyntaxNode Argument(string name, RefKind refKind, SyntaxNode expression); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public SyntaxNode Argument(RefKind refKind, SyntaxNode expression) => Argument(null, refKind, expression); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public SyntaxNode Argument(SyntaxNode expression) => Argument(null, RefKind.None, expression); /// <summary> /// Creates an expression that access an element of an array or indexer. /// </summary> public abstract SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates an expression that access an element of an array or indexer. /// </summary> public SyntaxNode ElementAccessExpression(SyntaxNode expression, params SyntaxNode[] arguments) => ElementAccessExpression(expression, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an expression that evaluates to the type at runtime. /// </summary> public abstract SyntaxNode TypeOfExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes an is-type-check operation. /// </summary> public abstract SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type); /// <summary> /// Creates an expression that denotes an is-type-check operation. /// </summary> public SyntaxNode IsTypeExpression(SyntaxNode expression, ITypeSymbol type) => IsTypeExpression(expression, TypeExpression(type)); /// <summary> /// Creates an expression that denotes an try-cast operation. /// </summary> public abstract SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type); /// <summary> /// Creates an expression that denotes an try-cast operation. /// </summary> public SyntaxNode TryCastExpression(SyntaxNode expression, ITypeSymbol type) => TryCastExpression(expression, TypeExpression(type)); /// <summary> /// Creates an expression that denotes a type cast operation. /// </summary> public abstract SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a type cast operation. /// </summary> public SyntaxNode CastExpression(ITypeSymbol type, SyntaxNode expression) => CastExpression(TypeExpression(type), expression); /// <summary> /// Creates an expression that denotes a type conversion operation. /// </summary> public abstract SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a type conversion operation. /// </summary> public SyntaxNode ConvertExpression(ITypeSymbol type, SyntaxNode expression) => ConvertExpression(TypeExpression(type), expression); /// <summary> /// Creates an expression that declares a value returning lambda expression. /// </summary> public abstract SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression); /// <summary> /// Creates an expression that declares a void returning lambda expression /// </summary> public abstract SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression); /// <summary> /// Creates an expression that declares a value returning lambda expression. /// </summary> public abstract SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates an expression that declares a void returning lambda expression. /// </summary> public abstract SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates an expression that declares a single parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(string parameterName, SyntaxNode expression) => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); /// <summary> /// Creates an expression that declares a single parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(string parameterName, SyntaxNode expression) => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); /// <summary> /// Creates an expression that declares a single parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(string parameterName, IEnumerable<SyntaxNode> statements) => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); /// <summary> /// Creates an expression that declares a single parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(string parameterName, IEnumerable<SyntaxNode> statements) => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); /// <summary> /// Creates an expression that declares a zero parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(SyntaxNode expression) => ValueReturningLambdaExpression((IEnumerable<SyntaxNode>)null, expression); /// <summary> /// Creates an expression that declares a zero parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(SyntaxNode expression) => VoidReturningLambdaExpression((IEnumerable<SyntaxNode>)null, expression); /// <summary> /// Creates an expression that declares a zero parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> statements) => ValueReturningLambdaExpression((IEnumerable<SyntaxNode>)null, statements); /// <summary> /// Creates an expression that declares a zero parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> statements) => VoidReturningLambdaExpression((IEnumerable<SyntaxNode>)null, statements); /// <summary> /// Creates a lambda parameter. /// </summary> public abstract SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null); /// <summary> /// Creates a lambda parameter. /// </summary> public SyntaxNode LambdaParameter(string identifier, ITypeSymbol type) => LambdaParameter(identifier, TypeExpression(type)); /// <summary> /// Creates an await expression. /// </summary> public abstract SyntaxNode AwaitExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => SyntaxGeneratorInternal.AddParentheses(expression, includeElasticTrivia, addSimplifierAnnotation); /// <summary> /// Creates an nameof expression. /// </summary> public abstract SyntaxNode NameOfExpression(SyntaxNode expression); /// <summary> /// Creates an tuple expression. /// </summary> public abstract SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments); /// <summary> /// Parses an expression from string /// </summary> internal abstract SyntaxNode ParseExpression(string stringToParse); internal abstract SyntaxTrivia Trivia(SyntaxNode node); internal abstract SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString); internal abstract SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// A language agnostic factory for creating syntax nodes. /// /// This API can be used to create language specific syntax nodes that are semantically /// similar between languages. /// /// The trees generated by this API will try to respect user preferences when /// possible. For example, generating <see cref="MemberAccessExpression(SyntaxNode, string)"/> /// will be done in a way such that "this." or "Me." will be simplified according to user /// preference if any <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)" /> /// overload is called. /// </summary> public abstract class SyntaxGenerator : ILanguageService { public static SyntaxRemoveOptions DefaultRemoveOptions = SyntaxRemoveOptions.KeepUnbalancedDirectives | SyntaxRemoveOptions.AddElasticMarker; internal abstract SyntaxTrivia CarriageReturnLineFeed { get; } internal abstract SyntaxTrivia ElasticCarriageReturnLineFeed { get; } internal abstract bool RequiresExplicitImplementationForInterfaceMembers { get; } internal ISyntaxFacts SyntaxFacts => SyntaxGeneratorInternal.SyntaxFacts; internal abstract SyntaxGeneratorInternal SyntaxGeneratorInternal { get; } internal abstract SyntaxTrivia Whitespace(string text); internal abstract SyntaxTrivia SingleLineComment(string text); internal abstract SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim); internal abstract SyntaxToken CreateInterpolatedStringEndToken(); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the specified language. /// </summary> public static SyntaxGenerator GetGenerator(Workspace workspace, string language) => workspace.Services.GetLanguageServices(language).GetService<SyntaxGenerator>(); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the document. /// </summary> public static SyntaxGenerator GetGenerator(Document document) => GetGenerator(document.Project); /// <summary> /// Gets the <see cref="SyntaxGenerator"/> for the language corresponding to the project. /// </summary> public static SyntaxGenerator GetGenerator(Project project) => project.LanguageServices.GetService<SyntaxGenerator>(); #region Declarations /// <summary> /// Returns the node if it is a declaration, the immediate enclosing declaration if one exists, or null. /// </summary> public SyntaxNode GetDeclaration(SyntaxNode node) { while (node != null) { if (GetDeclarationKind(node) != DeclarationKind.None) { return node; } else { node = node.Parent; } } return null; } /// <summary> /// Returns the enclosing declaration of the specified kind or null. /// </summary> public SyntaxNode GetDeclaration(SyntaxNode node, DeclarationKind kind) { while (node != null) { if (GetDeclarationKind(node) == kind) { return node; } else { node = node.Parent; } } return null; } /// <summary> /// Creates a field declaration. /// </summary> public abstract SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, SyntaxNode initializer = null); /// <summary> /// Creates a field declaration matching an existing field symbol. /// </summary> public SyntaxNode FieldDeclaration(IFieldSymbol field) { var initializer = field.HasConstantValue ? this.LiteralExpression(field.ConstantValue) : null; return FieldDeclaration(field, initializer); } /// <summary> /// Creates a field declaration matching an existing field symbol. /// </summary> public SyntaxNode FieldDeclaration(IFieldSymbol field, SyntaxNode initializer) { return FieldDeclaration( field.Name, TypeExpression(field.Type), field.DeclaredAccessibility, DeclarationModifiers.From(field), initializer); } //internal abstract SyntaxNode ObjectMemberInitializer(IEnumerable<SyntaxNode> fieldInitializers); //internal abstract SyntaxNode NamedFieldInitializer(SyntaxNode name, SyntaxNode value); //internal abstract SyntaxNode WithObjectCreationInitializer(SyntaxNode objectCreationExpression, SyntaxNode initializer); /// <summary> /// Creates a method declaration. /// </summary> public abstract SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters = null, IEnumerable<string> typeParameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Creates a method declaration matching an existing method symbol. /// </summary> public SyntaxNode MethodDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode> statements = null) => MethodDeclaration(method, method.Name, statements); internal SyntaxNode MethodDeclaration(IMethodSymbol method, string name, IEnumerable<SyntaxNode> statements = null) { var decl = MethodDeclaration( name, parameters: method.Parameters.Select(p => ParameterDeclaration(p)), returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType), accessibility: method.DeclaredAccessibility, modifiers: DeclarationModifiers.From(method), statements: statements); if (method.TypeParameters.Length > 0) { decl = this.WithTypeParametersAndConstraints(decl, method.TypeParameters); } if (method.ExplicitInterfaceImplementations.Length > 0) { decl = this.WithExplicitInterfaceImplementations(decl, ImmutableArray<ISymbol>.CastUp(method.ExplicitInterfaceImplementations)); } return decl; } /// <summary> /// Creates a method declaration. /// </summary> public virtual SyntaxNode OperatorDeclaration( OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { throw new NotImplementedException(); } /// <summary> /// Creates a method declaration matching an existing method symbol. /// </summary> public SyntaxNode OperatorDeclaration(IMethodSymbol method, IEnumerable<SyntaxNode> statements = null) { if (method.MethodKind != MethodKind.UserDefinedOperator) { throw new ArgumentException("Method is not an operator."); } var decl = OperatorDeclaration( GetOperatorKind(method), parameters: method.Parameters.Select(p => ParameterDeclaration(p)), returnType: method.ReturnType.IsSystemVoid() ? null : TypeExpression(method.ReturnType), accessibility: method.DeclaredAccessibility, modifiers: DeclarationModifiers.From(method), statements: statements); return decl; } private static OperatorKind GetOperatorKind(IMethodSymbol method) => method.Name switch { WellKnownMemberNames.ImplicitConversionName => OperatorKind.ImplicitConversion, WellKnownMemberNames.ExplicitConversionName => OperatorKind.ExplicitConversion, WellKnownMemberNames.AdditionOperatorName => OperatorKind.Addition, WellKnownMemberNames.BitwiseAndOperatorName => OperatorKind.BitwiseAnd, WellKnownMemberNames.BitwiseOrOperatorName => OperatorKind.BitwiseOr, WellKnownMemberNames.DecrementOperatorName => OperatorKind.Decrement, WellKnownMemberNames.DivisionOperatorName => OperatorKind.Division, WellKnownMemberNames.EqualityOperatorName => OperatorKind.Equality, WellKnownMemberNames.ExclusiveOrOperatorName => OperatorKind.ExclusiveOr, WellKnownMemberNames.FalseOperatorName => OperatorKind.False, WellKnownMemberNames.GreaterThanOperatorName => OperatorKind.GreaterThan, WellKnownMemberNames.GreaterThanOrEqualOperatorName => OperatorKind.GreaterThanOrEqual, WellKnownMemberNames.IncrementOperatorName => OperatorKind.Increment, WellKnownMemberNames.InequalityOperatorName => OperatorKind.Inequality, WellKnownMemberNames.LeftShiftOperatorName => OperatorKind.LeftShift, WellKnownMemberNames.LessThanOperatorName => OperatorKind.LessThan, WellKnownMemberNames.LessThanOrEqualOperatorName => OperatorKind.LessThanOrEqual, WellKnownMemberNames.LogicalNotOperatorName => OperatorKind.LogicalNot, WellKnownMemberNames.ModulusOperatorName => OperatorKind.Modulus, WellKnownMemberNames.MultiplyOperatorName => OperatorKind.Multiply, WellKnownMemberNames.OnesComplementOperatorName => OperatorKind.OnesComplement, WellKnownMemberNames.RightShiftOperatorName => OperatorKind.RightShift, WellKnownMemberNames.SubtractionOperatorName => OperatorKind.Subtraction, WellKnownMemberNames.TrueOperatorName => OperatorKind.True, WellKnownMemberNames.UnaryNegationOperatorName => OperatorKind.UnaryNegation, WellKnownMemberNames.UnaryPlusOperatorName => OperatorKind.UnaryPlus, _ => throw new ArgumentException("Unknown operator kind."), }; /// <summary> /// Creates a parameter declaration. /// </summary> public abstract SyntaxNode ParameterDeclaration( string name, SyntaxNode type = null, SyntaxNode initializer = null, RefKind refKind = RefKind.None); /// <summary> /// Creates a parameter declaration matching an existing parameter symbol. /// </summary> public SyntaxNode ParameterDeclaration(IParameterSymbol symbol, SyntaxNode initializer = null) { return ParameterDeclaration( symbol.Name, TypeExpression(symbol.Type), initializer, symbol.RefKind); } /// <summary> /// Creates a property declaration. The property will have a <c>get</c> accessor if /// <see cref="DeclarationModifiers.IsWriteOnly"/> is <see langword="false"/> and will have /// a <c>set</c> accessor if <see cref="DeclarationModifiers.IsReadOnly"/> is <see /// langword="false"/>. /// </summary> /// <remarks> /// In C# there is a distinction between passing in <see langword="null"/> for <paramref /// name="getAccessorStatements"/> or <paramref name="setAccessorStatements"/> versus /// passing in an empty list. <see langword="null"/> will produce an auto-property-accessor /// (i.e. <c>get;</c>) whereas an empty list will produce an accessor with an empty block /// (i.e. <c>get { }</c>). /// </remarks> public abstract SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null); /// <summary> /// Creates a property declaration using an existing property symbol as a signature. /// </summary> public SyntaxNode PropertyDeclaration( IPropertySymbol property, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null) { return PropertyDeclaration( property.Name, TypeExpression(property.Type), property.DeclaredAccessibility, DeclarationModifiers.From(property), getAccessorStatements, setAccessorStatements); } public SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, params SyntaxNode[] accessorDeclarations) => WithAccessorDeclarations(declaration, (IEnumerable<SyntaxNode>)accessorDeclarations); public abstract SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations); public abstract SyntaxNode GetAccessorDeclaration( Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> statements = null); public abstract SyntaxNode SetAccessorDeclaration( Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Creates an indexer declaration. /// </summary> public abstract SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null); /// <summary> /// Creates an indexer declaration matching an existing indexer symbol. /// </summary> public SyntaxNode IndexerDeclaration( IPropertySymbol indexer, IEnumerable<SyntaxNode> getAccessorStatements = null, IEnumerable<SyntaxNode> setAccessorStatements = null) { return IndexerDeclaration( indexer.Parameters.Select(p => this.ParameterDeclaration(p)), TypeExpression(indexer.Type), indexer.DeclaredAccessibility, DeclarationModifiers.From(indexer), getAccessorStatements, setAccessorStatements); } /// <summary> /// Creates a statement that adds the given handler to the given event. /// </summary> public abstract SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler); /// <summary> /// Creates a statement that removes the given handler from the given event. /// </summary> public abstract SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler); /// <summary> /// Creates an event declaration. /// </summary> public abstract SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default); /// <summary> /// Creates an event declaration from an existing event symbol /// </summary> public SyntaxNode EventDeclaration(IEventSymbol symbol) { return EventDeclaration( symbol.Name, TypeExpression(symbol.Type), symbol.DeclaredAccessibility, DeclarationModifiers.From(symbol)); } /// <summary> /// Creates a custom event declaration. /// </summary> public abstract SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> parameters = null, IEnumerable<SyntaxNode> addAccessorStatements = null, IEnumerable<SyntaxNode> removeAccessorStatements = null); /// <summary> /// Creates a custom event declaration from an existing event symbol. /// </summary> public SyntaxNode CustomEventDeclaration( IEventSymbol symbol, IEnumerable<SyntaxNode> addAccessorStatements = null, IEnumerable<SyntaxNode> removeAccessorStatements = null) { var invoke = symbol.Type.GetMembers("Invoke").FirstOrDefault(m => m.Kind == SymbolKind.Method) as IMethodSymbol; var parameters = invoke?.Parameters.Select(p => this.ParameterDeclaration(p)); return CustomEventDeclaration( symbol.Name, TypeExpression(symbol.Type), symbol.DeclaredAccessibility, DeclarationModifiers.From(symbol), parameters: parameters, addAccessorStatements: addAccessorStatements, removeAccessorStatements: removeAccessorStatements); } /// <summary> /// Creates a constructor declaration. /// </summary> public abstract SyntaxNode ConstructorDeclaration( string containingTypeName = null, IEnumerable<SyntaxNode> parameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> baseConstructorArguments = null, IEnumerable<SyntaxNode> statements = null); /// <summary> /// Create a constructor declaration using /// </summary> public SyntaxNode ConstructorDeclaration( IMethodSymbol constructorMethod, IEnumerable<SyntaxNode> baseConstructorArguments = null, IEnumerable<SyntaxNode> statements = null) { return ConstructorDeclaration( constructorMethod.ContainingType != null ? constructorMethod.ContainingType.Name : "New", constructorMethod.Parameters.Select(p => ParameterDeclaration(p)), constructorMethod.DeclaredAccessibility, DeclarationModifiers.From(constructorMethod), baseConstructorArguments, statements); } /// <summary> /// Converts method, property and indexer declarations into public interface implementations. /// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.) /// </summary> public SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType) => this.AsPublicInterfaceImplementation(declaration, interfaceType, null); /// <summary> /// Converts method, property and indexer declarations into public interface implementations. /// This is equivalent to an implicit C# interface implementation (you can access it via the interface or directly via the named member.) /// </summary> public abstract SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string interfaceMemberName); /// <summary> /// Converts method, property and indexer declarations into private interface implementations. /// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly). /// </summary> public SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType) => this.AsPrivateInterfaceImplementation(declaration, interfaceType, null); /// <summary> /// Converts method, property and indexer declarations into private interface implementations. /// This is equivalent to a C# explicit interface implementation (you can declare it for access via the interface, but cannot call it directly). /// </summary> public abstract SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceType, string interfaceMemberName); /// <summary> /// Creates a class declaration. /// </summary> public abstract SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, SyntaxNode baseType = null, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates a struct declaration. /// </summary> public abstract SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates a interface declaration. /// </summary> public abstract SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters = null, Accessibility accessibility = Accessibility.NotApplicable, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum declaration. /// </summary> public abstract SyntaxNode EnumDeclaration( string name, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum declaration /// </summary> internal abstract SyntaxNode EnumDeclaration( string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null); /// <summary> /// Creates an enum member /// </summary> public abstract SyntaxNode EnumMember(string name, SyntaxNode expression = null); /// <summary> /// Creates a delegate declaration. /// </summary> public abstract SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters = null, IEnumerable<string> typeParameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default); /// <summary> /// Creates a declaration matching an existing symbol. /// </summary> public SyntaxNode Declaration(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: return FieldDeclaration((IFieldSymbol)symbol); case SymbolKind.Property: var property = (IPropertySymbol)symbol; if (property.IsIndexer) { return IndexerDeclaration(property); } else { return PropertyDeclaration(property); } case SymbolKind.Event: var ev = (IEventSymbol)symbol; return EventDeclaration(ev); case SymbolKind.Method: var method = (IMethodSymbol)symbol; switch (method.MethodKind) { case MethodKind.Constructor: case MethodKind.SharedConstructor: return ConstructorDeclaration(method); case MethodKind.Ordinary: return MethodDeclaration(method); case MethodKind.UserDefinedOperator: return OperatorDeclaration(method); } break; case SymbolKind.Parameter: return ParameterDeclaration((IParameterSymbol)symbol); case SymbolKind.NamedType: var type = (INamedTypeSymbol)symbol; SyntaxNode declaration = null; switch (type.TypeKind) { case TypeKind.Class: declaration = ClassDeclaration( type.Name, accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type), baseType: TypeExpression(type.BaseType), interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Struct: declaration = StructDeclaration( type.Name, accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type), interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Interface: declaration = InterfaceDeclaration( type.Name, accessibility: type.DeclaredAccessibility, interfaceTypes: type.Interfaces.Select(i => TypeExpression(i)), members: type.GetMembers().Where(CanBeDeclared).Select(m => Declaration(m))); break; case TypeKind.Enum: declaration = EnumDeclaration( type.Name, type.EnumUnderlyingType?.SpecialType == SpecialType.System_Int32 ? null : TypeExpression(type.EnumUnderlyingType.SpecialType), accessibility: type.DeclaredAccessibility, members: type.GetMembers().Where(s => s.Kind == SymbolKind.Field).Select(m => Declaration(m))); break; case TypeKind.Delegate: var invoke = type.GetMembers("Invoke").First() as IMethodSymbol; declaration = DelegateDeclaration( type.Name, parameters: invoke.Parameters.Select(p => ParameterDeclaration(p)), returnType: TypeExpression(invoke.ReturnType), accessibility: type.DeclaredAccessibility, modifiers: DeclarationModifiers.From(type)); break; } if (declaration != null) { return WithTypeParametersAndConstraints(declaration, type.TypeParameters); } break; } throw new ArgumentException("Symbol cannot be converted to a declaration"); } private static bool CanBeDeclared(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: case SymbolKind.Parameter: return true; case SymbolKind.Method: var method = (IMethodSymbol)symbol; switch (method.MethodKind) { case MethodKind.Constructor: case MethodKind.SharedConstructor: case MethodKind.Ordinary: return true; } break; case SymbolKind.NamedType: var type = (INamedTypeSymbol)symbol; switch (type.TypeKind) { case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Enum: case TypeKind.Delegate: return true; } break; } return false; } private SyntaxNode WithTypeParametersAndConstraints(SyntaxNode declaration, ImmutableArray<ITypeParameterSymbol> typeParameters) { if (typeParameters.Length > 0) { declaration = WithTypeParameters(declaration, typeParameters.Select(tp => tp.Name)); foreach (var tp in typeParameters) { if (tp.HasConstructorConstraint || tp.HasReferenceTypeConstraint || tp.HasValueTypeConstraint || tp.ConstraintTypes.Length > 0) { declaration = this.WithTypeConstraint(declaration, tp.Name, kinds: (tp.HasConstructorConstraint ? SpecialTypeConstraintKind.Constructor : SpecialTypeConstraintKind.None) | (tp.HasReferenceTypeConstraint ? SpecialTypeConstraintKind.ReferenceType : SpecialTypeConstraintKind.None) | (tp.HasValueTypeConstraint ? SpecialTypeConstraintKind.ValueType : SpecialTypeConstraintKind.None), types: tp.ConstraintTypes.Select(t => TypeExpression(t))); } } } return declaration; } internal abstract SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations); /// <summary> /// Converts a declaration (method, class, etc) into a declaration with type parameters. /// </summary> public abstract SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameters); /// <summary> /// Converts a declaration (method, class, etc) into a declaration with type parameters. /// </summary> public SyntaxNode WithTypeParameters(SyntaxNode declaration, params string[] typeParameters) => WithTypeParameters(declaration, (IEnumerable<string>)typeParameters); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public abstract SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types = null); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, params SyntaxNode[] types) => WithTypeConstraint(declaration, typeParameterName, kinds, (IEnumerable<SyntaxNode>)types); /// <summary> /// Adds a type constraint to a type parameter of a declaration. /// </summary> public SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, params SyntaxNode[] types) => WithTypeConstraint(declaration, typeParameterName, SpecialTypeConstraintKind.None, (IEnumerable<SyntaxNode>)types); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public abstract SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(SyntaxNode name, params SyntaxNode[] declarations) => NamespaceDeclaration(name, (IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(string name, IEnumerable<SyntaxNode> declarations) => NamespaceDeclaration(DottedName(name), declarations); /// <summary> /// Creates a namespace declaration. /// </summary> /// <param name="name">The name of the namespace.</param> /// <param name="declarations">Zero or more namespace or type declarations.</param> public SyntaxNode NamespaceDeclaration(string name, params SyntaxNode[] declarations) => NamespaceDeclaration(DottedName(name), (IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a compilation unit declaration /// </summary> /// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param> public abstract SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations); /// <summary> /// Creates a compilation unit declaration /// </summary> /// <param name="declarations">Zero or more namespace import, namespace or type declarations.</param> public SyntaxNode CompilationUnit(params SyntaxNode[] declarations) => CompilationUnit((IEnumerable<SyntaxNode>)declarations); /// <summary> /// Creates a namespace import declaration. /// </summary> /// <param name="name">The name of the namespace being imported.</param> public abstract SyntaxNode NamespaceImportDeclaration(SyntaxNode name); /// <summary> /// Creates a namespace import declaration. /// </summary> /// <param name="name">The name of the namespace being imported.</param> public SyntaxNode NamespaceImportDeclaration(string name) => NamespaceImportDeclaration(DottedName(name)); /// <summary> /// Creates an alias import declaration. /// </summary> /// <param name="aliasIdentifierName">The name of the alias.</param> /// <param name="symbol">The namespace or type to be aliased.</param> public SyntaxNode AliasImportDeclaration(string aliasIdentifierName, INamespaceOrTypeSymbol symbol) => AliasImportDeclaration(aliasIdentifierName, NameExpression(symbol)); /// <summary> /// Creates an alias import declaration. /// </summary> /// <param name="aliasIdentifierName">The name of the alias.</param> /// <param name="name">The namespace or type to be aliased.</param> public abstract SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name); /// <summary> /// Creates an attribute. /// </summary> public abstract SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments = null); /// <summary> /// Creates an attribute. /// </summary> public SyntaxNode Attribute(string name, IEnumerable<SyntaxNode> attributeArguments = null) => Attribute(DottedName(name), attributeArguments); /// <summary> /// Creates an attribute. /// </summary> public SyntaxNode Attribute(string name, params SyntaxNode[] attributeArguments) => Attribute(name, (IEnumerable<SyntaxNode>)attributeArguments); /// <summary> /// Creates an attribute matching existing attribute data. /// </summary> public SyntaxNode Attribute(AttributeData attribute) { var args = attribute.ConstructorArguments.Select(a => this.AttributeArgument(this.TypedConstantExpression(a))) .Concat(attribute.NamedArguments.Select(n => this.AttributeArgument(n.Key, this.TypedConstantExpression(n.Value)))) .ToBoxedImmutableArray(); return Attribute( name: this.TypeExpression(attribute.AttributeClass), attributeArguments: args.Count > 0 ? args : null); } /// <summary> /// Creates an attribute argument. /// </summary> public abstract SyntaxNode AttributeArgument(string name, SyntaxNode expression); /// <summary> /// Creates an attribute argument. /// </summary> public SyntaxNode AttributeArgument(SyntaxNode expression) => AttributeArgument(null, expression); /// <summary> /// Removes all attributes from the declaration, including return attributes. /// </summary> public SyntaxNode RemoveAllAttributes(SyntaxNode declaration) => this.RemoveNodes(declaration, this.GetAttributes(declaration).Concat(this.GetReturnAttributes(declaration))); /// <summary> /// Removes comments from leading and trailing trivia, as well /// as potentially removing comments from opening and closing tokens. /// </summary> internal abstract SyntaxNode RemoveAllComments(SyntaxNode node); internal SyntaxNode RemoveLeadingAndTrailingComments(SyntaxNode node) { return node.WithLeadingTrivia(RemoveCommentLines(node.GetLeadingTrivia())) .WithTrailingTrivia(RemoveCommentLines(node.GetTrailingTrivia())); } internal SyntaxToken RemoveLeadingAndTrailingComments(SyntaxToken token) { return token.WithLeadingTrivia(RemoveCommentLines(token.LeadingTrivia)) .WithTrailingTrivia(RemoveCommentLines(token.TrailingTrivia)); } internal abstract SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList); internal abstract bool IsRegularOrDocComment(SyntaxTrivia trivia); internal SyntaxNode RemoveAllTypeInheritance(SyntaxNode declaration) => this.RemoveNodes(declaration, this.GetTypeInheritance(declaration)); internal abstract ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration); /// <summary> /// Gets the attributes of a declaration, not including the return attributes. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the attributes inserted. /// </summary> public abstract SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes); /// <summary> /// Creates a new instance of the declaration with the attributes inserted. /// </summary> public SyntaxNode InsertAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes) => this.InsertAttributes(declaration, index, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Creates a new instance of a declaration with the specified attributes added. /// </summary> public SyntaxNode AddAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes) => this.InsertAttributes(declaration, this.GetAttributes(declaration).Count, attributes); /// <summary> /// Creates a new instance of a declaration with the specified attributes added. /// </summary> public SyntaxNode AddAttributes(SyntaxNode declaration, params SyntaxNode[] attributes) => AddAttributes(declaration, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Gets the return attributes from the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration); /// <summary> /// Creates a new instance of a method declaration with return attributes inserted. /// </summary> public abstract SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes); /// <summary> /// Creates a new instance of a method declaration with return attributes inserted. /// </summary> public SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, params SyntaxNode[] attributes) => this.InsertReturnAttributes(declaration, index, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Creates a new instance of a method declaration with return attributes added. /// </summary> public SyntaxNode AddReturnAttributes(SyntaxNode declaration, IEnumerable<SyntaxNode> attributes) => this.InsertReturnAttributes(declaration, this.GetReturnAttributes(declaration).Count, attributes); /// <summary> /// Creates a new instance of a method declaration node with return attributes added. /// </summary> public SyntaxNode AddReturnAttributes(SyntaxNode declaration, params SyntaxNode[] attributes) => AddReturnAttributes(declaration, (IEnumerable<SyntaxNode>)attributes); /// <summary> /// Gets the attribute arguments for the attribute declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration); /// <summary> /// Creates a new instance of the attribute with the arguments inserted. /// </summary> public abstract SyntaxNode InsertAttributeArguments(SyntaxNode attributeDeclaration, int index, IEnumerable<SyntaxNode> attributeArguments); /// <summary> /// Creates a new instance of the attribute with the arguments added. /// </summary> public SyntaxNode AddAttributeArguments(SyntaxNode attributeDeclaration, IEnumerable<SyntaxNode> attributeArguments) => this.InsertAttributeArguments(attributeDeclaration, this.GetAttributeArguments(attributeDeclaration).Count, attributeArguments); /// <summary> /// Gets the namespace imports that are part of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the namespace imports inserted. /// </summary> public abstract SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports inserted. /// </summary> public SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, params SyntaxNode[] imports) => this.InsertNamespaceImports(declaration, index, (IEnumerable<SyntaxNode>)imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports added. /// </summary> public SyntaxNode AddNamespaceImports(SyntaxNode declaration, IEnumerable<SyntaxNode> imports) => this.InsertNamespaceImports(declaration, this.GetNamespaceImports(declaration).Count, imports); /// <summary> /// Creates a new instance of the declaration with the namespace imports added. /// </summary> public SyntaxNode AddNamespaceImports(SyntaxNode declaration, params SyntaxNode[] imports) => this.AddNamespaceImports(declaration, (IEnumerable<SyntaxNode>)imports); /// <summary> /// Gets the current members of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration); /// <summary> /// Creates a new instance of the declaration with the members inserted. /// </summary> public abstract SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members); /// <summary> /// Creates a new instance of the declaration with the members inserted. /// </summary> public SyntaxNode InsertMembers(SyntaxNode declaration, int index, params SyntaxNode[] members) => this.InsertMembers(declaration, index, (IEnumerable<SyntaxNode>)members); /// <summary> /// Creates a new instance of the declaration with the members added to the end. /// </summary> public SyntaxNode AddMembers(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => this.InsertMembers(declaration, this.GetMembers(declaration).Count, members); /// <summary> /// Creates a new instance of the declaration with the members added to the end. /// </summary> public SyntaxNode AddMembers(SyntaxNode declaration, params SyntaxNode[] members) => this.AddMembers(declaration, (IEnumerable<SyntaxNode>)members); /// <summary> /// Gets the accessibility of the declaration. /// </summary> public abstract Accessibility GetAccessibility(SyntaxNode declaration); /// <summary> /// Changes the accessibility of the declaration. /// </summary> public abstract SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility); /// <summary> /// Gets the <see cref="DeclarationModifiers"/> for the declaration. /// </summary> public abstract DeclarationModifiers GetModifiers(SyntaxNode declaration); /// <summary> /// Changes the <see cref="DeclarationModifiers"/> for the declaration. /// </summary> public abstract SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers); /// <summary> /// Gets the <see cref="DeclarationKind"/> for the declaration. /// </summary> public abstract DeclarationKind GetDeclarationKind(SyntaxNode declaration); /// <summary> /// Gets the name of the declaration. /// </summary> public abstract string GetName(SyntaxNode declaration); /// <summary> /// Changes the name of the declaration. /// </summary> public abstract SyntaxNode WithName(SyntaxNode declaration, string name); /// <summary> /// Gets the type of the declaration. /// </summary> public abstract SyntaxNode GetType(SyntaxNode declaration); /// <summary> /// Changes the type of the declaration. /// </summary> public abstract SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type); /// <summary> /// Gets the list of parameters for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration); internal abstract SyntaxNode GetParameterListNode(SyntaxNode declaration); /// <summary> /// Inserts the parameters at the specified index into the declaration. /// </summary> public abstract SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters); /// <summary> /// Adds the parameters to the declaration. /// </summary> public SyntaxNode AddParameters(SyntaxNode declaration, IEnumerable<SyntaxNode> parameters) => this.InsertParameters(declaration, this.GetParameters(declaration).Count, parameters); /// <summary> /// Gets the list of switch sections for the statement. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement); /// <summary> /// Inserts the switch sections at the specified index into the statement. /// </summary> public abstract SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections); /// <summary> /// Adds the switch sections to the statement. /// </summary> public SyntaxNode AddSwitchSections(SyntaxNode switchStatement, IEnumerable<SyntaxNode> switchSections) => this.InsertSwitchSections(switchStatement, this.GetSwitchSections(switchStatement).Count, switchSections); /// <summary> /// Gets the expression associated with the declaration. /// </summary> public abstract SyntaxNode GetExpression(SyntaxNode declaration); /// <summary> /// Changes the expression associated with the declaration. /// </summary> public abstract SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression); /// <summary> /// Gets the statements for the body of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the declaration. /// </summary> public abstract SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets the accessors for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration); /// <summary> /// Gets the accessor of the specified kind for the declaration. /// </summary> public SyntaxNode GetAccessor(SyntaxNode declaration, DeclarationKind kind) => this.GetAccessors(declaration).FirstOrDefault(a => GetDeclarationKind(a) == kind); /// <summary> /// Creates a new instance of the declaration with the accessors inserted. /// </summary> public abstract SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors); /// <summary> /// Creates a new instance of the declaration with the accessors added. /// </summary> public SyntaxNode AddAccessors(SyntaxNode declaration, IEnumerable<SyntaxNode> accessors) => this.InsertAccessors(declaration, this.GetAccessors(declaration).Count, accessors); /// <summary> /// Gets the statements for the body of the get-accessor of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the get-accessor of the declaration. /// </summary> public abstract SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets the statements for the body of the set-accessor of the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration); /// <summary> /// Changes the statements for the body of the set-accessor of the declaration. /// </summary> public abstract SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements); /// <summary> /// Gets a list of the base and interface types for the declaration. /// </summary> public abstract IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration); /// <summary> /// Adds a base type to the declaration /// </summary> public abstract SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType); /// <summary> /// Adds an interface type to the declaration /// </summary> public abstract SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType); internal abstract SyntaxNode AsInterfaceMember(SyntaxNode member); #endregion #region Remove, Replace, Insert /// <summary> /// Replaces the node in the root's tree with the new node. /// </summary> public virtual SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode node, SyntaxNode newDeclaration) { if (newDeclaration != null) { return root.ReplaceNode(node, newDeclaration); } else { return this.RemoveNode(root, node); } } internal static SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.ReplaceNode(node, newDeclarations); /// <summary> /// Inserts the new node before the specified declaration. /// </summary> public virtual SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.InsertNodesBefore(node, newDeclarations); /// <summary> /// Inserts the new node before the specified declaration. /// </summary> public virtual SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> newDeclarations) => root.InsertNodesAfter(node, newDeclarations); /// <summary> /// Removes the node from the sub tree starting at the root. /// </summary> public virtual SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => RemoveNode(root, node, DefaultRemoveOptions); /// <summary> /// Removes the node from the sub tree starting at the root. /// </summary> public virtual SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) => root.RemoveNode(node, options); /// <summary> /// Removes all the declarations from the sub tree starting at the root. /// </summary> public SyntaxNode RemoveNodes(SyntaxNode root, IEnumerable<SyntaxNode> declarations) { var newRoot = root.TrackNodes(declarations); foreach (var decl in declarations) { newRoot = this.RemoveNode(newRoot, newRoot.GetCurrentNode(decl)); } return newRoot; } #endregion #region Utility internal abstract SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) where TElement : SyntaxNode; internal abstract SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) where TElement : SyntaxNode; internal static SyntaxTokenList Merge(SyntaxTokenList original, SyntaxTokenList newList) { // return tokens from newList, but use original tokens of kind matches return new SyntaxTokenList(newList.Select( token => Any(original, token.RawKind) ? original.First(tk => tk.RawKind == token.RawKind) : token)); } private static bool Any(SyntaxTokenList original, int rawKind) { foreach (var token in original) { if (token.RawKind == rawKind) { return true; } } return false; } protected static SyntaxNode PreserveTrivia<TNode>(TNode node, Func<TNode, SyntaxNode> nodeChanger) where TNode : SyntaxNode { if (node == null) { return node; } var nodeWithoutTrivia = node.WithoutLeadingTrivia().WithoutTrailingTrivia(); var changedNode = nodeChanger(nodeWithoutTrivia); if (changedNode == nodeWithoutTrivia) { return node; } else { return changedNode .WithLeadingTrivia(node.GetLeadingTrivia().Concat(changedNode.GetLeadingTrivia())) .WithTrailingTrivia(changedNode.GetTrailingTrivia().Concat(node.GetTrailingTrivia())); } } protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxNode original, SyntaxNode replacement) { var combinedTriviaReplacement = replacement.WithLeadingTrivia(original.GetLeadingTrivia().AddRange(replacement.GetLeadingTrivia())) .WithTrailingTrivia(replacement.GetTrailingTrivia().AddRange(original.GetTrailingTrivia())); return root.ReplaceNode(original, combinedTriviaReplacement); } protected static SyntaxNode ReplaceWithTrivia<TNode>(SyntaxNode root, TNode original, Func<TNode, SyntaxNode> replacer) where TNode : SyntaxNode { return ReplaceWithTrivia(root, original, replacer(original)); } protected static SyntaxNode ReplaceWithTrivia(SyntaxNode root, SyntaxToken original, SyntaxToken replacement) { var combinedTriviaReplacement = replacement.WithLeadingTrivia(original.LeadingTrivia.AddRange(replacement.LeadingTrivia)) .WithTrailingTrivia(replacement.TrailingTrivia.AddRange(original.TrailingTrivia)); return root.ReplaceToken(original, combinedTriviaReplacement); } /// <summary> /// Creates a new instance of the node with the leading and trailing trivia removed and replaced with elastic markers. /// </summary> public abstract TNode ClearTrivia<TNode>(TNode node) where TNode : SyntaxNode; #pragma warning disable CA1822 // Mark members as static - shipped public API protected int IndexOf<T>(IReadOnlyList<T> list, T element) #pragma warning restore CA1822 // Mark members as static { for (int i = 0, count = list.Count; i < count; i++) { if (EqualityComparer<T>.Default.Equals(list[i], element)) { return i; } } return -1; } protected static SyntaxNode ReplaceRange(SyntaxNode root, SyntaxNode node, IEnumerable<SyntaxNode> replacements) { var first = replacements.First(); var trackedFirst = first.TrackNodes(first); var newRoot = root.ReplaceNode(node, trackedFirst); var currentFirst = newRoot.GetCurrentNode(first); return newRoot.InsertNodesAfter(currentFirst, replacements.Skip(1)); } protected static SeparatedSyntaxList<TNode> RemoveRange<TNode>(SeparatedSyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { for (; count > 0 && offset < list.Count; count--) { list = list.RemoveAt(offset); } return list; } protected static SyntaxList<TNode> RemoveRange<TNode>(SyntaxList<TNode> list, int offset, int count) where TNode : SyntaxNode { for (; count > 0 && offset < list.Count; count--) { list = list.RemoveAt(offset); } return list; } #endregion #region Statements /// <summary> /// Creates statement that allows an expression to execute in a statement context. /// This is typically an invocation or assignment expression. /// </summary> /// <param name="expression">The expression that is to be executed. This is usually a method invocation expression.</param> public abstract SyntaxNode ExpressionStatement(SyntaxNode expression); /// <summary> /// Creates a statement that can be used to return a value from a method body. /// </summary> /// <param name="expression">An optional expression that can be returned.</param> public abstract SyntaxNode ReturnStatement(SyntaxNode expression = null); /// <summary> /// Creates a statement that can be used to yield a value from an iterator method. /// </summary> /// <param name="expression">An expression that can be yielded.</param> internal SyntaxNode YieldReturnStatement(SyntaxNode expression) => SyntaxGeneratorInternal.YieldReturnStatement(expression); /// <summary> /// Creates a statement that can be used to throw an exception. /// </summary> /// <param name="expression">An optional expression that can be thrown.</param> public abstract SyntaxNode ThrowStatement(SyntaxNode expression = null); /// <summary> /// Creates an expression that can be used to throw an exception. /// </summary> public abstract SyntaxNode ThrowExpression(SyntaxNode expression); /// <summary> /// True if <see cref="ThrowExpression"/> can be used /// </summary> internal abstract bool SupportsThrowExpression(); /// <summary> /// <see langword="true"/> if the language requires a <see cref="TypeExpression(ITypeSymbol)"/> /// (including <see langword="var"/>) to be stated when making a /// <see cref="LocalDeclarationStatement(ITypeSymbol, string, SyntaxNode, bool)"/>. /// <see langword="false"/> if the language allows the type node to be entirely elided. /// </summary> internal bool RequiresLocalDeclarationType() => SyntaxGeneratorInternal.RequiresLocalDeclarationType(); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public abstract SyntaxNode LocalDeclarationStatement( SyntaxNode type, string identifier, SyntaxNode initializer = null, bool isConst = false); internal SyntaxNode LocalDeclarationStatement( SyntaxNode type, SyntaxToken identifier, SyntaxNode initializer = null, bool isConst = false) => SyntaxGeneratorInternal.LocalDeclarationStatement(type, identifier, initializer, isConst); internal SyntaxNode WithInitializer(SyntaxNode variableDeclarator, SyntaxNode initializer) => SyntaxGeneratorInternal.WithInitializer(variableDeclarator, initializer); internal SyntaxNode EqualsValueClause(SyntaxToken operatorToken, SyntaxNode value) => SyntaxGeneratorInternal.EqualsValueClause(operatorToken, value); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public SyntaxNode LocalDeclarationStatement( ITypeSymbol type, string name, SyntaxNode initializer = null, bool isConst = false) => LocalDeclarationStatement(TypeExpression(type), name, initializer, isConst); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> public SyntaxNode LocalDeclarationStatement(string name, SyntaxNode initializer) => LocalDeclarationStatement((SyntaxNode)null, name, initializer); /// <summary> /// Creates a statement that declares a single local variable. /// </summary> internal SyntaxNode LocalDeclarationStatement(SyntaxToken name, SyntaxNode initializer) => LocalDeclarationStatement((SyntaxNode)null, name, initializer); /// <summary> /// Creates an if-statement /// </summary> /// <param name="condition">A condition expression.</param> /// <param name="trueStatements">The statements that are executed if the condition is true.</param> /// <param name="falseStatements">The statements that are executed if the condition is false.</param> public abstract SyntaxNode IfStatement( SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null); /// <summary> /// Creates an if statement /// </summary> /// <param name="condition">A condition expression.</param> /// <param name="trueStatements">The statements that are executed if the condition is true.</param> /// <param name="falseStatement">A single statement that is executed if the condition is false.</param> public SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, SyntaxNode falseStatement) => IfStatement(condition, trueStatements, new[] { falseStatement }); /// <summary> /// Creates a switch statement that branches to individual sections based on the value of the specified expression. /// </summary> public abstract SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> sections); /// <summary> /// Creates a switch statement that branches to individual sections based on the value of the specified expression. /// </summary> public SyntaxNode SwitchStatement(SyntaxNode expression, params SyntaxNode[] sections) => SwitchStatement(expression, (IEnumerable<SyntaxNode>)sections); /// <summary> /// Creates a section for a switch statement. /// </summary> public abstract SyntaxNode SwitchSection(IEnumerable<SyntaxNode> caseExpressions, IEnumerable<SyntaxNode> statements); internal abstract SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a single-case section a switch statement. /// </summary> public SyntaxNode SwitchSection(SyntaxNode caseExpression, IEnumerable<SyntaxNode> statements) => SwitchSection(new[] { caseExpression }, statements); /// <summary> /// Creates a default section for a switch statement. /// </summary> public abstract SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements); /// <summary> /// Create a statement that exits a switch statement and continues after it. /// </summary> public abstract SyntaxNode ExitSwitchStatement(); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public abstract SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public SyntaxNode UsingStatement(string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) => UsingStatement(null, name, expression, statements); /// <summary> /// Creates a statement that represents a using-block pattern. /// </summary> public abstract SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a statement that represents a lock-block pattern. /// </summary> public abstract SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a try-catch or try-catch-finally statement. /// </summary> public abstract SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null); /// <summary> /// Creates a try-catch or try-catch-finally statement. /// </summary> public SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, params SyntaxNode[] catchClauses) => TryCatchStatement(tryStatements, (IEnumerable<SyntaxNode>)catchClauses); /// <summary> /// Creates a try-finally statement. /// </summary> public SyntaxNode TryFinallyStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> finallyStatements) => TryCatchStatement(tryStatements, catchClauses: null, finallyStatements: finallyStatements); /// <summary> /// Creates a catch-clause. /// </summary> public abstract SyntaxNode CatchClause(SyntaxNode type, string identifier, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a catch-clause. /// </summary> public SyntaxNode CatchClause(ITypeSymbol type, string identifier, IEnumerable<SyntaxNode> statements) => CatchClause(TypeExpression(type), identifier, statements); /// <summary> /// Creates a while-loop statement /// </summary> public abstract SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates a block of statements. Not supported in VB. /// </summary> internal abstract SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements); #endregion #region Expressions internal abstract SyntaxToken NumericLiteralToken(string text, ulong value); internal SyntaxToken InterpolatedStringTextToken(string content, string value) => SyntaxGeneratorInternal.InterpolatedStringTextToken(content, value); internal SyntaxNode InterpolatedStringText(SyntaxToken textToken) => SyntaxGeneratorInternal.InterpolatedStringText(textToken); internal SyntaxNode Interpolation(SyntaxNode syntaxNode) => SyntaxGeneratorInternal.Interpolation(syntaxNode); internal SyntaxNode InterpolatedStringExpression(SyntaxToken startToken, IEnumerable<SyntaxNode> content, SyntaxToken endToken) => SyntaxGeneratorInternal.InterpolatedStringExpression(startToken, content, endToken); internal SyntaxNode InterpolationAlignmentClause(SyntaxNode alignment) => SyntaxGeneratorInternal.InterpolationAlignmentClause(alignment); internal SyntaxNode InterpolationFormatClause(string format) => SyntaxGeneratorInternal.InterpolationFormatClause(format); /// <summary> /// An expression that represents the default value of a type. /// This is typically a null value for reference types or a zero-filled value for value types. /// </summary> public abstract SyntaxNode DefaultExpression(SyntaxNode type); public abstract SyntaxNode DefaultExpression(ITypeSymbol type); /// <summary> /// Creates an expression that denotes the containing method's this-parameter. /// </summary> public abstract SyntaxNode ThisExpression(); /// <summary> /// Creates an expression that denotes the containing method's base-parameter. /// </summary> public abstract SyntaxNode BaseExpression(); /// <summary> /// Creates a literal expression. This is typically numeric primitives, strings or chars. /// </summary> public abstract SyntaxNode LiteralExpression(object value); /// <summary> /// Creates an expression for a typed constant. /// </summary> public abstract SyntaxNode TypedConstantExpression(TypedConstant value); /// <summary> /// Creates an expression that denotes the boolean false literal. /// </summary> public SyntaxNode FalseLiteralExpression() => LiteralExpression(false); /// <summary> /// Creates an expression that denotes the boolean true literal. /// </summary> public SyntaxNode TrueLiteralExpression() => LiteralExpression(true); /// <summary> /// Creates an expression that denotes the null literal. /// </summary> public SyntaxNode NullLiteralExpression() => LiteralExpression(null); /// <summary> /// Creates an expression that denotes a simple identifier name. /// </summary> /// <param name="identifier"></param> /// <returns></returns> public abstract SyntaxNode IdentifierName(string identifier); internal abstract SyntaxNode IdentifierName(SyntaxToken identifier); internal SyntaxToken Identifier(string identifier) => SyntaxGeneratorInternal.Identifier(identifier); internal abstract SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public abstract SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments); internal abstract SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, IEnumerable<ITypeSymbol> typeArguments) => GenericName(identifier, typeArguments.Select(ta => TypeExpression(ta))); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, params SyntaxNode[] typeArguments) => GenericName(identifier, (IEnumerable<SyntaxNode>)typeArguments); /// <summary> /// Creates an expression that denotes a generic identifier name. /// </summary> public SyntaxNode GenericName(string identifier, params ITypeSymbol[] typeArguments) => GenericName(identifier, (IEnumerable<ITypeSymbol>)typeArguments); /// <summary> /// Converts an expression that ends in a name into an expression that ends in a generic name. /// If the expression already ends in a generic name, the new type arguments are used instead. /// </summary> public abstract SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments); /// <summary> /// Converts an expression that ends in a name into an expression that ends in a generic name. /// If the expression already ends in a generic name, the new type arguments are used instead. /// </summary> public SyntaxNode WithTypeArguments(SyntaxNode expression, params SyntaxNode[] typeArguments) => WithTypeArguments(expression, (IEnumerable<SyntaxNode>)typeArguments); /// <summary> /// Creates a name expression that denotes a qualified name. /// The left operand can be any name expression. /// The right operand can be either and identifier or generic name. /// </summary> public abstract SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns a new name node qualified with the 'global' alias ('Global' in VB). /// </summary> internal abstract SyntaxNode GlobalAliasedName(SyntaxNode name); /// <summary> /// Creates a name expression from a dotted name string. /// </summary> public SyntaxNode DottedName(string dottedName) { if (dottedName == null) { throw new ArgumentNullException(nameof(dottedName)); } var parts = dottedName.Split(s_dotSeparator); SyntaxNode name = null; foreach (var part in parts) { if (name == null) { name = IdentifierName(part); } else { name = QualifiedName(name, IdentifierName(part)).WithAdditionalAnnotations(Simplification.Simplifier.Annotation); } } return name; } private static readonly char[] s_dotSeparator = new char[] { '.' }; /// <summary> /// Creates a name that denotes a type or namespace. /// </summary> /// <param name="namespaceOrTypeSymbol">The symbol to create a name for.</param> /// <returns></returns> public abstract SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol); /// <summary> /// Creates an expression that denotes a type. /// </summary> public abstract SyntaxNode TypeExpression(ITypeSymbol typeSymbol); /// <summary> /// Creates an expression that denotes a type. If addImport is false, /// adds a <see cref="DoNotAddImportsAnnotation"/> which will prevent any /// imports or usings from being added for the type. /// </summary> public SyntaxNode TypeExpression(ITypeSymbol typeSymbol, bool addImport) { var expression = TypeExpression(typeSymbol); return addImport ? expression : expression.WithAdditionalAnnotations(DoNotAddImportsAnnotation.Annotation); } /// <summary> /// Creates an expression that denotes a special type name. /// </summary> public abstract SyntaxNode TypeExpression(SpecialType specialType); /// <summary> /// Creates an expression that denotes an array type. /// </summary> public abstract SyntaxNode ArrayTypeExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes a nullable type. /// </summary> public abstract SyntaxNode NullableTypeExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(IEnumerable<SyntaxNode> elements) { if (elements == null) { throw new ArgumentNullException(nameof(elements)); } if (elements.Count() <= 1) { throw new ArgumentException("Tuples must have at least two elements.", nameof(elements)); } return CreateTupleType(elements); } internal abstract SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(params SyntaxNode[] elements) => TupleTypeExpression((IEnumerable<SyntaxNode>)elements); /// <summary> /// Creates an expression that denotes a tuple type. /// </summary> public SyntaxNode TupleTypeExpression(IEnumerable<ITypeSymbol> elementTypes, IEnumerable<string> elementNames = null) { if (elementTypes == null) { throw new ArgumentNullException(nameof(elementTypes)); } if (elementNames != null) { if (elementNames.Count() != elementTypes.Count()) { throw new ArgumentException("The number of element names must match the cardinality of the tuple.", nameof(elementNames)); } return TupleTypeExpression(elementTypes.Zip(elementNames, (type, name) => TupleElementExpression(type, name))); } return TupleTypeExpression(elementTypes.Select(type => TupleElementExpression(type, name: null))); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates an expression that denotes a tuple element. /// </summary> public abstract SyntaxNode TupleElementExpression(SyntaxNode type, string name = null); /// <summary> /// Creates an expression that denotes a tuple element. /// </summary> public SyntaxNode TupleElementExpression(ITypeSymbol type, string name = null) => TupleElementExpression(TypeExpression(type), name); #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Creates an expression that denotes an assignment from the right argument to left argument. /// </summary> public abstract SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a value-type equality test operation. /// </summary> public abstract SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a reference-type equality test operation. /// </summary> public abstract SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a value-type inequality test operation. /// </summary> public abstract SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a reference-type inequality test operation. /// </summary> public abstract SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a less-than test operation. /// </summary> public abstract SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a less-than-or-equal test operation. /// </summary> public abstract SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a greater-than test operation. /// </summary> public abstract SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a greater-than-or-equal test operation. /// </summary> public abstract SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a unary negation operation. /// </summary> public abstract SyntaxNode NegateExpression(SyntaxNode expression); /// <summary> /// Creates an expression that denotes an addition operation. /// </summary> public abstract SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes an subtraction operation. /// </summary> public abstract SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a multiplication operation. /// </summary> public abstract SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a division operation. /// </summary> public abstract SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a modulo operation. /// </summary> public abstract SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-and operation. /// </summary> public abstract SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-or operation. /// </summary> public abstract SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a bitwise-not operation /// </summary> public abstract SyntaxNode BitwiseNotExpression(SyntaxNode operand); /// <summary> /// Creates an expression that denotes a logical-and operation. /// </summary> public abstract SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a logical-or operation. /// </summary> public abstract SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates an expression that denotes a logical not operation. /// </summary> public abstract SyntaxNode LogicalNotExpression(SyntaxNode expression); /// <summary> /// Creates an expression that denotes a conditional evaluation operation. /// </summary> public abstract SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse); /// <summary> /// Creates an expression that denotes a conditional access operation. Use <see /// cref="MemberBindingExpression"/> and <see /// cref="ElementBindingExpression(IEnumerable{SyntaxNode})"/> to generate the <paramref /// name="whenNotNull"/> argument. /// </summary> public abstract SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull); /// <summary> /// Creates an expression that denotes a member binding operation. /// </summary> public abstract SyntaxNode MemberBindingExpression(SyntaxNode name); /// <summary> /// Creates an expression that denotes an element binding operation. /// </summary> public abstract SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates an expression that denotes an element binding operation. /// </summary> public SyntaxNode ElementBindingExpression(params SyntaxNode[] arguments) => ElementBindingExpression((IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an expression that denotes a coalesce operation. /// </summary> public abstract SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right); /// <summary> /// Creates a member access expression. /// </summary> public virtual SyntaxNode MemberAccessExpression(SyntaxNode expression, SyntaxNode memberName) { return MemberAccessExpressionWorker(expression, memberName) .WithAdditionalAnnotations(Simplification.Simplifier.Annotation); } internal abstract SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode memberName); internal SyntaxNode RefExpression(SyntaxNode expression) => SyntaxGeneratorInternal.RefExpression(expression); /// <summary> /// Creates a member access expression. /// </summary> public SyntaxNode MemberAccessExpression(SyntaxNode expression, string memberName) => MemberAccessExpression(expression, IdentifierName(memberName)); /// <summary> /// Creates an array creation expression for a single dimensional array of specified size. /// </summary> public abstract SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size); /// <summary> /// Creates an array creation expression for a single dimensional array with specified initial element values. /// </summary> public abstract SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements); /// <summary> /// Creates an object creation expression. /// </summary> public abstract SyntaxNode ObjectCreationExpression(SyntaxNode namedType, IEnumerable<SyntaxNode> arguments); internal abstract SyntaxNode ObjectCreationExpression( SyntaxNode namedType, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(ITypeSymbol type, IEnumerable<SyntaxNode> arguments) => ObjectCreationExpression(TypeExpression(type), arguments); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(SyntaxNode type, params SyntaxNode[] arguments) => ObjectCreationExpression(type, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an object creation expression. /// </summary> public SyntaxNode ObjectCreationExpression(ITypeSymbol type, params SyntaxNode[] arguments) => ObjectCreationExpression(type, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates a invocation expression. /// </summary> public abstract SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates a invocation expression /// </summary> public SyntaxNode InvocationExpression(SyntaxNode expression, params SyntaxNode[] arguments) => InvocationExpression(expression, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public abstract SyntaxNode Argument(string name, RefKind refKind, SyntaxNode expression); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public SyntaxNode Argument(RefKind refKind, SyntaxNode expression) => Argument(null, refKind, expression); /// <summary> /// Creates a node that is an argument to an invocation. /// </summary> public SyntaxNode Argument(SyntaxNode expression) => Argument(null, RefKind.None, expression); /// <summary> /// Creates an expression that access an element of an array or indexer. /// </summary> public abstract SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments); /// <summary> /// Creates an expression that access an element of an array or indexer. /// </summary> public SyntaxNode ElementAccessExpression(SyntaxNode expression, params SyntaxNode[] arguments) => ElementAccessExpression(expression, (IEnumerable<SyntaxNode>)arguments); /// <summary> /// Creates an expression that evaluates to the type at runtime. /// </summary> public abstract SyntaxNode TypeOfExpression(SyntaxNode type); /// <summary> /// Creates an expression that denotes an is-type-check operation. /// </summary> public abstract SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type); /// <summary> /// Creates an expression that denotes an is-type-check operation. /// </summary> public SyntaxNode IsTypeExpression(SyntaxNode expression, ITypeSymbol type) => IsTypeExpression(expression, TypeExpression(type)); /// <summary> /// Creates an expression that denotes an try-cast operation. /// </summary> public abstract SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type); /// <summary> /// Creates an expression that denotes an try-cast operation. /// </summary> public SyntaxNode TryCastExpression(SyntaxNode expression, ITypeSymbol type) => TryCastExpression(expression, TypeExpression(type)); /// <summary> /// Creates an expression that denotes a type cast operation. /// </summary> public abstract SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a type cast operation. /// </summary> public SyntaxNode CastExpression(ITypeSymbol type, SyntaxNode expression) => CastExpression(TypeExpression(type), expression); /// <summary> /// Creates an expression that denotes a type conversion operation. /// </summary> public abstract SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression); /// <summary> /// Creates an expression that denotes a type conversion operation. /// </summary> public SyntaxNode ConvertExpression(ITypeSymbol type, SyntaxNode expression) => ConvertExpression(TypeExpression(type), expression); /// <summary> /// Creates an expression that declares a value returning lambda expression. /// </summary> public abstract SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression); /// <summary> /// Creates an expression that declares a void returning lambda expression /// </summary> public abstract SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression); /// <summary> /// Creates an expression that declares a value returning lambda expression. /// </summary> public abstract SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates an expression that declares a void returning lambda expression. /// </summary> public abstract SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements); /// <summary> /// Creates an expression that declares a single parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(string parameterName, SyntaxNode expression) => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); /// <summary> /// Creates an expression that declares a single parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(string parameterName, SyntaxNode expression) => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, expression); /// <summary> /// Creates an expression that declares a single parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(string parameterName, IEnumerable<SyntaxNode> statements) => ValueReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); /// <summary> /// Creates an expression that declares a single parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(string parameterName, IEnumerable<SyntaxNode> statements) => VoidReturningLambdaExpression(new[] { LambdaParameter(parameterName) }, statements); /// <summary> /// Creates an expression that declares a zero parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(SyntaxNode expression) => ValueReturningLambdaExpression((IEnumerable<SyntaxNode>)null, expression); /// <summary> /// Creates an expression that declares a zero parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(SyntaxNode expression) => VoidReturningLambdaExpression((IEnumerable<SyntaxNode>)null, expression); /// <summary> /// Creates an expression that declares a zero parameter value returning lambda expression. /// </summary> public SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> statements) => ValueReturningLambdaExpression((IEnumerable<SyntaxNode>)null, statements); /// <summary> /// Creates an expression that declares a zero parameter void returning lambda expression. /// </summary> public SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> statements) => VoidReturningLambdaExpression((IEnumerable<SyntaxNode>)null, statements); /// <summary> /// Creates a lambda parameter. /// </summary> public abstract SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null); /// <summary> /// Creates a lambda parameter. /// </summary> public SyntaxNode LambdaParameter(string identifier, ITypeSymbol type) => LambdaParameter(identifier, TypeExpression(type)); /// <summary> /// Creates an await expression. /// </summary> public abstract SyntaxNode AwaitExpression(SyntaxNode expression); /// <summary> /// Wraps with parens. /// </summary> internal SyntaxNode AddParentheses(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => SyntaxGeneratorInternal.AddParentheses(expression, includeElasticTrivia, addSimplifierAnnotation); /// <summary> /// Creates an nameof expression. /// </summary> public abstract SyntaxNode NameOfExpression(SyntaxNode expression); /// <summary> /// Creates an tuple expression. /// </summary> public abstract SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments); /// <summary> /// Parses an expression from string /// </summary> internal abstract SyntaxNode ParseExpression(string stringToParse); internal abstract SyntaxTrivia Trivia(SyntaxNode node); internal abstract SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString); internal abstract SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content); #endregion } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal abstract class AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { // NOTE: This is a trigger diagnostic, which doesn't show up in the ruleset editor and hence doesn't need a conventional IDE Diagnostic ID string. internal const string DiagnosticFixableId = "RemoveUnnecessaryImportsFixable"; // The NotConfigurable custom tag ensures that user can't turn this diagnostic into a warning / error via // ruleset editor or solution explorer. Setting messageFormat to empty string ensures that we won't display // this diagnostic in the preview pane header. #pragma warning disable RS0030 // Do not used banned APIs - We cannot use AbstractBuiltInCodeStyleDiagnosticAnalyzer nor AbstractCodeQualityDiagnosticAnalyzer. // This analyzer is run against generated code while the abstract base classes mentioned doesn't. private static readonly DiagnosticDescriptor s_fixableIdDescriptor = new(DiagnosticFixableId, title: "", messageFormat: "", category: "", defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs protected abstract LocalizableString GetTitleAndMessageFormatForClassificationIdDescriptor(); protected abstract ImmutableArray<SyntaxNode> MergeImports(ImmutableArray<SyntaxNode> unnecessaryImports); protected abstract bool IsRegularCommentOrDocComment(SyntaxTrivia trivia); protected abstract IUnnecessaryImportsProvider UnnecessaryImportsProvider { get; } private DiagnosticDescriptor _unnecessaryClassificationIdDescriptor; private DiagnosticDescriptor _classificationIdDescriptor; private DiagnosticDescriptor _unnecessaryGeneratedCodeClassificationIdDescriptor; private DiagnosticDescriptor _generatedCodeClassificationIdDescriptor; private void EnsureClassificationIdDescriptors() { if (_unnecessaryClassificationIdDescriptor == null) { var titleAndMessageFormat = GetTitleAndMessageFormatForClassificationIdDescriptor(); #pragma warning disable RS0030 // Do not used banned APIs _unnecessaryClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()).ToArray()); _classificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()); _unnecessaryGeneratedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.UnnecessaryAndNotConfigurable); _generatedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { EnsureClassificationIdDescriptors(); return ImmutableArray.Create( s_fixableIdDescriptor, _unnecessaryClassificationIdDescriptor, _classificationIdDescriptor, _unnecessaryGeneratedCodeClassificationIdDescriptor, _generatedCodeClassificationIdDescriptor); } } public bool OpenFileOnly(OptionSet options) => false; public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSemanticModelAction(AnalyzeSemanticModel); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var language = context.SemanticModel.Language; var unnecessaryImports = UnnecessaryImportsProvider.GetUnnecessaryImports(context.SemanticModel, cancellationToken); if (unnecessaryImports.Any()) { // The IUnnecessaryImportsService will return individual import pieces that // need to be removed. For example, it will return individual import-clauses // from VB. However, we want to mark the entire import statement if we are // going to remove all the clause. Defer to our subclass to stitch this up // for us appropriately. unnecessaryImports = MergeImports(unnecessaryImports); EnsureClassificationIdDescriptors(); var fadeOut = ShouldFade(context.Options, tree, language, cancellationToken); DiagnosticDescriptor descriptor; if (GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocComment, cancellationToken)) { descriptor = fadeOut ? _unnecessaryGeneratedCodeClassificationIdDescriptor : _generatedCodeClassificationIdDescriptor; } else { descriptor = fadeOut ? _unnecessaryClassificationIdDescriptor : _classificationIdDescriptor; } var getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unnecessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree, descriptor, cancellationToken).Concat( CreateFixableDiagnostics(unnecessaryImports, tree, cancellationToken)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } static bool ShouldFade(AnalyzerOptions options, SyntaxTree tree, string language, CancellationToken cancellationToken) { return options.GetOption(FadingOptions.FadeOutUnusedImports, language, tree, cancellationToken); } } protected virtual Func<SyntaxNode, SyntaxToken> GetLastTokenDelegateForContiguousSpans() => null; // Create one diagnostic for each unnecessary span that will be classified as Unnecessary private static IEnumerable<Diagnostic> CreateClassificationDiagnostics( IEnumerable<TextSpan> contiguousSpans, SyntaxTree tree, DiagnosticDescriptor descriptor, CancellationToken cancellationToken) { foreach (var span in contiguousSpans) { if (tree.OverlapsHiddenPosition(span, cancellationToken)) { continue; } yield return Diagnostic.Create(descriptor, tree.GetLocation(span)); } } protected abstract IEnumerable<TextSpan> GetFixableDiagnosticSpans( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken); private IEnumerable<Diagnostic> CreateFixableDiagnostics( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken) { var spans = GetFixableDiagnosticSpans(nodes, tree, cancellationToken); foreach (var span in spans) { yield return Diagnostic.Create(s_fixableIdDescriptor, tree.GetLocation(span)); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal abstract class AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { // NOTE: This is a trigger diagnostic, which doesn't show up in the ruleset editor and hence doesn't need a conventional IDE Diagnostic ID string. internal const string DiagnosticFixableId = "RemoveUnnecessaryImportsFixable"; // The NotConfigurable custom tag ensures that user can't turn this diagnostic into a warning / error via // ruleset editor or solution explorer. Setting messageFormat to empty string ensures that we won't display // this diagnostic in the preview pane header. #pragma warning disable RS0030 // Do not used banned APIs - We cannot use AbstractBuiltInCodeStyleDiagnosticAnalyzer nor AbstractCodeQualityDiagnosticAnalyzer. // This analyzer is run against generated code while the abstract base classes mentioned doesn't. private static readonly DiagnosticDescriptor s_fixableIdDescriptor = new(DiagnosticFixableId, title: "", messageFormat: "", category: "", defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs protected abstract LocalizableString GetTitleAndMessageFormatForClassificationIdDescriptor(); protected abstract ImmutableArray<SyntaxNode> MergeImports(ImmutableArray<SyntaxNode> unnecessaryImports); protected abstract bool IsRegularCommentOrDocComment(SyntaxTrivia trivia); protected abstract IUnnecessaryImportsProvider UnnecessaryImportsProvider { get; } private DiagnosticDescriptor _unnecessaryClassificationIdDescriptor; private DiagnosticDescriptor _classificationIdDescriptor; private DiagnosticDescriptor _unnecessaryGeneratedCodeClassificationIdDescriptor; private DiagnosticDescriptor _generatedCodeClassificationIdDescriptor; private void EnsureClassificationIdDescriptors() { if (_unnecessaryClassificationIdDescriptor == null) { var titleAndMessageFormat = GetTitleAndMessageFormatForClassificationIdDescriptor(); #pragma warning disable RS0030 // Do not used banned APIs _unnecessaryClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()).ToArray()); _classificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()); _unnecessaryGeneratedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.UnnecessaryAndNotConfigurable); _generatedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs } } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { EnsureClassificationIdDescriptors(); return ImmutableArray.Create( s_fixableIdDescriptor, _unnecessaryClassificationIdDescriptor, _classificationIdDescriptor, _unnecessaryGeneratedCodeClassificationIdDescriptor, _generatedCodeClassificationIdDescriptor); } } public bool OpenFileOnly(OptionSet options) => false; public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSemanticModelAction(AnalyzeSemanticModel); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var language = context.SemanticModel.Language; var unnecessaryImports = UnnecessaryImportsProvider.GetUnnecessaryImports(context.SemanticModel, cancellationToken); if (unnecessaryImports.Any()) { // The IUnnecessaryImportsService will return individual import pieces that // need to be removed. For example, it will return individual import-clauses // from VB. However, we want to mark the entire import statement if we are // going to remove all the clause. Defer to our subclass to stitch this up // for us appropriately. unnecessaryImports = MergeImports(unnecessaryImports); EnsureClassificationIdDescriptors(); var fadeOut = ShouldFade(context.Options, tree, language, cancellationToken); DiagnosticDescriptor descriptor; if (GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocComment, cancellationToken)) { descriptor = fadeOut ? _unnecessaryGeneratedCodeClassificationIdDescriptor : _generatedCodeClassificationIdDescriptor; } else { descriptor = fadeOut ? _unnecessaryClassificationIdDescriptor : _classificationIdDescriptor; } var getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unnecessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree, descriptor, cancellationToken).Concat( CreateFixableDiagnostics(unnecessaryImports, tree, cancellationToken)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } static bool ShouldFade(AnalyzerOptions options, SyntaxTree tree, string language, CancellationToken cancellationToken) { return options.GetOption(FadingOptions.FadeOutUnusedImports, language, tree, cancellationToken); } } protected virtual Func<SyntaxNode, SyntaxToken> GetLastTokenDelegateForContiguousSpans() => null; // Create one diagnostic for each unnecessary span that will be classified as Unnecessary private static IEnumerable<Diagnostic> CreateClassificationDiagnostics( IEnumerable<TextSpan> contiguousSpans, SyntaxTree tree, DiagnosticDescriptor descriptor, CancellationToken cancellationToken) { foreach (var span in contiguousSpans) { if (tree.OverlapsHiddenPosition(span, cancellationToken)) { continue; } yield return Diagnostic.Create(descriptor, tree.GetLocation(span)); } } protected abstract IEnumerable<TextSpan> GetFixableDiagnosticSpans( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken); private IEnumerable<Diagnostic> CreateFixableDiagnostics( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken) { var spans = GetFixableDiagnosticSpans(nodes, tree, cancellationToken); foreach (var span in spans) { yield return Diagnostic.Create(s_fixableIdDescriptor, tree.GetLocation(span)); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/EditAndContinue/SyntaxComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class SyntaxComparer : AbstractSyntaxComparer { internal static readonly SyntaxComparer TopLevel = new(null, null, null, null, compareStatementSyntax: false); internal static readonly SyntaxComparer Statement = new(null, null, null, null, compareStatementSyntax: true); /// <summary> /// Creates a syntax comparer /// </summary> /// <param name="oldRoot">The root node to start comparisons from</param> /// <param name="newRoot">The new root node to compare against</param> /// <param name="oldRootChildren">Child nodes that should always be compared</param> /// <param name="newRootChildren">New child nodes to compare against</param> /// <param name="compareStatementSyntax">Whether this comparer is in "statement mode"</param> public SyntaxComparer( SyntaxNode? oldRoot, SyntaxNode? newRoot, IEnumerable<SyntaxNode>? oldRootChildren, IEnumerable<SyntaxNode>? newRootChildren, bool compareStatementSyntax) : base(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax) { } protected override bool IsLambdaBodyStatementOrExpression(SyntaxNode node) => LambdaUtilities.IsLambdaBodyStatementOrExpression(node); #region Labels // Assumptions: // - Each listed label corresponds to one or more syntax kinds. // - Nodes with same labels might produce Update edits, nodes with different labels don't. // - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. // (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). // - All descendants of a node whose kind is listed here will be ignored regardless of their labels internal enum Label { // Top level syntax kinds CompilationUnit, GlobalStatement, NamespaceDeclaration, ExternAliasDirective, // tied to parent UsingDirective, // tied to parent TypeDeclaration, EnumDeclaration, DelegateDeclaration, FieldDeclaration, // tied to parent FieldVariableDeclaration, // tied to parent FieldVariableDeclarator, // tied to parent MethodDeclaration, // tied to parent OperatorDeclaration, // tied to parent ConversionOperatorDeclaration, // tied to parent ConstructorDeclaration, // tied to parent DestructorDeclaration, // tied to parent PropertyDeclaration, // tied to parent IndexerDeclaration, // tied to parent EventDeclaration, // tied to parent EnumMemberDeclaration, // tied to parent AccessorList, // tied to parent AccessorDeclaration, // tied to parent // Statement syntax kinds Block, CheckedStatement, UnsafeStatement, TryStatement, CatchClause, // tied to parent CatchDeclaration, // tied to parent CatchFilterClause, // tied to parent FinallyClause, // tied to parent ForStatement, ForStatementPart, // tied to parent ForEachStatement, UsingStatement, FixedStatement, LockStatement, WhileStatement, DoStatement, IfStatement, ElseClause, // tied to parent SwitchStatement, SwitchSection, CasePatternSwitchLabel, // tied to parent SwitchExpression, SwitchExpressionArm, // tied to parent WhenClause, // tied to parent YieldStatement, // tied to parent GotoStatement, GotoCaseStatement, BreakContinueStatement, ReturnThrowStatement, ExpressionStatement, LabeledStatement, // TODO: // Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.) // Also consider handling LocalDeclarationStatement as just a bag of variable declarators, // so that variable declarators contained in one can be matched with variable declarators contained in the other. LocalDeclarationStatement, // tied to parent LocalVariableDeclaration, // tied to parent LocalVariableDeclarator, // tied to parent SingleVariableDesignation, AwaitExpression, NestedFunction, FromClause, QueryBody, FromClauseLambda, // tied to parent LetClauseLambda, // tied to parent WhereClauseLambda, // tied to parent OrderByClause, // tied to parent OrderingLambda, // tied to parent SelectClauseLambda, // tied to parent JoinClauseLambda, // tied to parent JoinIntoClause, // tied to parent GroupClauseLambda, // tied to parent QueryContinuation, // tied to parent // Syntax kinds that are common to both statement and top level TypeParameterList, // tied to parent TypeParameterConstraintClause, // tied to parent TypeParameter, // tied to parent ParameterList, // tied to parent BracketedParameterList, // tied to parent Parameter, // tied to parent AttributeList, // tied to parent Attribute, // tied to parent // helpers: Count, Ignored = IgnoredNode } /// <summary> /// Return 1 if it is desirable to report two edits (delete and insert) rather than a move edit /// when the node changes its parent. /// </summary> private static int TiedToAncestor(Label label) { switch (label) { // Top level syntax case Label.ExternAliasDirective: case Label.UsingDirective: case Label.FieldDeclaration: case Label.FieldVariableDeclaration: case Label.FieldVariableDeclarator: case Label.MethodDeclaration: case Label.OperatorDeclaration: case Label.ConversionOperatorDeclaration: case Label.ConstructorDeclaration: case Label.DestructorDeclaration: case Label.PropertyDeclaration: case Label.IndexerDeclaration: case Label.EventDeclaration: case Label.EnumMemberDeclaration: case Label.AccessorDeclaration: case Label.AccessorList: case Label.TypeParameterList: case Label.TypeParameter: case Label.TypeParameterConstraintClause: case Label.ParameterList: case Label.BracketedParameterList: case Label.Parameter: case Label.AttributeList: case Label.Attribute: return 1; // Statement syntax case Label.LocalDeclarationStatement: case Label.LocalVariableDeclaration: case Label.LocalVariableDeclarator: case Label.GotoCaseStatement: case Label.BreakContinueStatement: case Label.ElseClause: case Label.CatchClause: case Label.CatchDeclaration: case Label.CatchFilterClause: case Label.FinallyClause: case Label.ForStatementPart: case Label.YieldStatement: case Label.FromClauseLambda: case Label.LetClauseLambda: case Label.WhereClauseLambda: case Label.OrderByClause: case Label.OrderingLambda: case Label.SelectClauseLambda: case Label.JoinClauseLambda: case Label.JoinIntoClause: case Label.GroupClauseLambda: case Label.QueryContinuation: case Label.CasePatternSwitchLabel: case Label.WhenClause: case Label.SwitchExpressionArm: return 1; default: return 0; } } internal override int Classify(int kind, SyntaxNode? node, out bool isLeaf) => (int)Classify((SyntaxKind)kind, node, out isLeaf); internal Label Classify(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart". // We need to capture it in the match since these expressions can be "active statements" and as such we need to map them. // // The parent is not available only when comparing nodes for value equality. if (node != null && node.Parent.IsKind(SyntaxKind.ForStatement) && node is ExpressionSyntax) { return Label.ForStatementPart; } // ************************************ // Top and statement syntax // ************************************ // These nodes can appear during top level and statement processing, so we put them in this first // switch for simplicity. Statement specific, and top level specific cases are handled below. switch (kind) { case SyntaxKind.CompilationUnit: return Label.CompilationUnit; case SyntaxKind.TypeParameterList: return Label.TypeParameterList; case SyntaxKind.TypeParameterConstraintClause: return Label.TypeParameterConstraintClause; case SyntaxKind.TypeParameter: // not a leaf because an attribute may be applied return Label.TypeParameter; case SyntaxKind.BracketedParameterList: return Label.BracketedParameterList; case SyntaxKind.ParameterList: return Label.ParameterList; case SyntaxKind.Parameter: return Label.Parameter; case SyntaxKind.ConstructorDeclaration: // Root when matching constructor bodies. return Label.ConstructorDeclaration; } if (_compareStatementSyntax) { return ClassifyStatementSyntax(kind, node, out isLeaf); } return ClassifyTopSyntax(kind, node, out isLeaf); } private static Label ClassifyStatementSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // ************************************ // Statement syntax // ************************************ // These nodes could potentially be seen as top level syntax, but we only want them labelled // during statement syntax so they have to be kept separate. // // For example when top level sees something like this: // // private int X => new Func(() => { return 1 })(); // // It needs to go through the entire lambda to know if that property def has changed // but if we start labelling things, like ReturnStatement in the above example, then // it will stop. Given that a block bodied lambda can have any statements a user likes // the whole set has to be dealt with separately. switch (kind) { // Notes: // A descendant of a leaf node may be a labeled node that we don't want to visit if // we are comparing its parent node (used for lambda bodies). // // Expressions are ignored but they may contain nodes that should be matched by tree comparer. // (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren. case SyntaxKind.NamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: // These declarations can come after global statements so we want to stop statement matching // because no global statements can come after them isLeaf = true; return Label.Ignored; case SyntaxKind.LocalDeclarationStatement: return Label.LocalDeclarationStatement; case SyntaxKind.SingleVariableDesignation: return Label.SingleVariableDesignation; case SyntaxKind.LabeledStatement: return Label.LabeledStatement; case SyntaxKind.EmptyStatement: isLeaf = true; return Label.ExpressionStatement; case SyntaxKind.GotoStatement: isLeaf = true; return Label.GotoStatement; case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: isLeaf = true; return Label.GotoCaseStatement; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: isLeaf = true; return Label.BreakContinueStatement; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: return Label.ReturnThrowStatement; case SyntaxKind.ExpressionStatement: return Label.ExpressionStatement; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: return Label.YieldStatement; case SyntaxKind.DoStatement: return Label.DoStatement; case SyntaxKind.WhileStatement: return Label.WhileStatement; case SyntaxKind.ForStatement: return Label.ForStatement; case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForEachStatement: return Label.ForEachStatement; case SyntaxKind.UsingStatement: return Label.UsingStatement; case SyntaxKind.FixedStatement: return Label.FixedStatement; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return Label.CheckedStatement; case SyntaxKind.UnsafeStatement: return Label.UnsafeStatement; case SyntaxKind.LockStatement: return Label.LockStatement; case SyntaxKind.IfStatement: return Label.IfStatement; case SyntaxKind.ElseClause: return Label.ElseClause; case SyntaxKind.SwitchStatement: return Label.SwitchStatement; case SyntaxKind.SwitchSection: return Label.SwitchSection; case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: // Switch labels are included in the "value" of the containing switch section. // We don't need to analyze case expressions. isLeaf = true; return Label.Ignored; case SyntaxKind.WhenClause: return Label.WhenClause; case SyntaxKind.CasePatternSwitchLabel: return Label.CasePatternSwitchLabel; case SyntaxKind.SwitchExpression: return Label.SwitchExpression; case SyntaxKind.SwitchExpressionArm: return Label.SwitchExpressionArm; case SyntaxKind.TryStatement: return Label.TryStatement; case SyntaxKind.CatchClause: return Label.CatchClause; case SyntaxKind.CatchDeclaration: // the declarator of the exception variable return Label.CatchDeclaration; case SyntaxKind.CatchFilterClause: return Label.CatchFilterClause; case SyntaxKind.FinallyClause: return Label.FinallyClause; case SyntaxKind.FromClause: // The first from clause of a query is not a lambda. // We have to assign it a label different from "FromClauseLambda" // so that we won't match lambda-from to non-lambda-from. // // Since FromClause declares range variables we need to include it in the map, // so that we are able to map range variable declarations. // Therefore we assign it a dedicated label. // // The parent is not available only when comparing nodes for value equality. // In that case it doesn't matter what label the node has as long as it has some. if (node == null || node.Parent.IsKind(SyntaxKind.QueryExpression)) { return Label.FromClause; } return Label.FromClauseLambda; case SyntaxKind.QueryBody: return Label.QueryBody; case SyntaxKind.QueryContinuation: return Label.QueryContinuation; case SyntaxKind.LetClause: return Label.LetClauseLambda; case SyntaxKind.WhereClause: return Label.WhereClauseLambda; case SyntaxKind.OrderByClause: return Label.OrderByClause; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return Label.OrderingLambda; case SyntaxKind.SelectClause: return Label.SelectClauseLambda; case SyntaxKind.JoinClause: return Label.JoinClauseLambda; case SyntaxKind.JoinIntoClause: return Label.JoinIntoClause; case SyntaxKind.GroupClause: return Label.GroupClauseLambda; case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: case SyntaxKind.GenericName: case SyntaxKind.TypeArgumentList: case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: case SyntaxKind.PointerType: case SyntaxKind.NullableType: case SyntaxKind.TupleType: case SyntaxKind.RefType: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.NameColon: case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.ConstantPattern: case SyntaxKind.DiscardDesignation: // can't contain a lambda/await/anonymous type: isLeaf = true; return Label.Ignored; case SyntaxKind.AwaitExpression: return Label.AwaitExpression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: return Label.NestedFunction; case SyntaxKind.VariableDeclaration: return Label.LocalVariableDeclaration; case SyntaxKind.VariableDeclarator: return Label.LocalVariableDeclarator; case SyntaxKind.Block: return Label.Block; } // If we got this far, its an unlabelled node. Since just about any node can // contain a lambda, isLeaf must be false for statement syntax. return Label.Ignored; } private static Label ClassifyTopSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // ************************************ // Top syntax // ************************************ // More the most part these nodes will only appear in top syntax but its easier to // keep them separate so we can more easily discern was is shared, above. switch (kind) { case SyntaxKind.GlobalStatement: isLeaf = true; return Label.GlobalStatement; case SyntaxKind.ExternAliasDirective: isLeaf = true; return Label.ExternAliasDirective; case SyntaxKind.UsingDirective: isLeaf = true; return Label.UsingDirective; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Label.NamespaceDeclaration; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return Label.TypeDeclaration; case SyntaxKind.MethodDeclaration: return Label.MethodDeclaration; case SyntaxKind.EnumDeclaration: return Label.EnumDeclaration; case SyntaxKind.DelegateDeclaration: return Label.DelegateDeclaration; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return Label.FieldDeclaration; case SyntaxKind.ConversionOperatorDeclaration: return Label.ConversionOperatorDeclaration; case SyntaxKind.OperatorDeclaration: return Label.OperatorDeclaration; case SyntaxKind.DestructorDeclaration: isLeaf = true; return Label.DestructorDeclaration; case SyntaxKind.PropertyDeclaration: return Label.PropertyDeclaration; case SyntaxKind.IndexerDeclaration: return Label.IndexerDeclaration; case SyntaxKind.EventDeclaration: return Label.EventDeclaration; case SyntaxKind.EnumMemberDeclaration: // not a leaf because an attribute may be applied return Label.EnumMemberDeclaration; case SyntaxKind.AccessorList: return Label.AccessorList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: isLeaf = true; return Label.AccessorDeclaration; // Note: These last two do actually appear as statement syntax, but mean something // different and hence have a different label case SyntaxKind.VariableDeclaration: return Label.FieldVariableDeclaration; case SyntaxKind.VariableDeclarator: // For top syntax, a variable declarator is a leaf node isLeaf = true; return Label.FieldVariableDeclarator; case SyntaxKind.AttributeList: // Only module/assembly attributes are labelled if (node is not null && node.IsParentKind(SyntaxKind.CompilationUnit)) { return Label.AttributeList; } break; case SyntaxKind.Attribute: // Only module/assembly attributes are labelled if (node is { Parent: { } parent } && parent.IsParentKind(SyntaxKind.CompilationUnit)) { isLeaf = true; return Label.Attribute; } break; } // If we got this far, its an unlabelled node. For top // syntax, we don't need to descend into any ignored nodes isLeaf = true; return Label.Ignored; } // internal for testing internal bool HasLabel(SyntaxKind kind) => Classify(kind, node: null, out _) != Label.Ignored; protected internal override int LabelCount => (int)Label.Count; protected internal override int TiedToAncestor(int label) => TiedToAncestor((Label)label); #endregion #region Comparisons public override bool ValuesEqual(SyntaxNode left, SyntaxNode right) { Func<SyntaxKind, bool>? ignoreChildFunction; switch (left.Kind()) { // all syntax kinds with a method body child: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // When comparing method bodies we need to NOT ignore VariableDeclaration and VariableDeclarator children, // but when comparing field definitions we should ignore VariableDeclarations children. var leftBody = GetBody(left); var rightBody = GetBody(right); if (!SyntaxFactory.AreEquivalent(leftBody, rightBody, null)) { return false; } ignoreChildFunction = childKind => childKind == SyntaxKind.Block || childKind == SyntaxKind.ArrowExpressionClause || HasLabel(childKind); break; case SyntaxKind.SwitchSection: return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right); case SyntaxKind.ForStatement: // The only children of ForStatement are labeled nodes and punctuation. return true; default: if (HasChildren(left)) { ignoreChildFunction = childKind => HasLabel(childKind); } else { ignoreChildFunction = null; } break; } return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction); } private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right) { return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null) && SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: HasLabel); } private static SyntaxNode? GetBody(SyntaxNode node) { switch (node) { case BaseMethodDeclarationSyntax baseMethodDeclarationSyntax: return baseMethodDeclarationSyntax.Body ?? (SyntaxNode?)baseMethodDeclarationSyntax.ExpressionBody?.Expression; case AccessorDeclarationSyntax accessorDeclarationSyntax: return accessorDeclarationSyntax.Body ?? (SyntaxNode?)accessorDeclarationSyntax.ExpressionBody?.Expression; default: throw ExceptionUtilities.UnexpectedValue(node); } } protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance) { switch (leftNode.Kind()) { case SyntaxKind.VariableDeclarator: distance = ComputeDistance( ((VariableDeclaratorSyntax)leftNode).Identifier, ((VariableDeclaratorSyntax)rightNode).Identifier); return true; case SyntaxKind.ForStatement: var leftFor = (ForStatementSyntax)leftNode; var rightFor = (ForStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFor, rightFor); return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: { var leftForEach = (CommonForEachStatementSyntax)leftNode; var rightForEach = (CommonForEachStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftForEach, rightForEach); return true; } case SyntaxKind.UsingStatement: var leftUsing = (UsingStatementSyntax)leftNode; var rightUsing = (UsingStatementSyntax)rightNode; if (leftUsing.Declaration != null && rightUsing.Declaration != null) { distance = ComputeWeightedDistance( leftUsing.Declaration, leftUsing.Statement, rightUsing.Declaration, rightUsing.Statement); } else { distance = ComputeWeightedDistance( (SyntaxNode?)leftUsing.Expression ?? leftUsing.Declaration!, leftUsing.Statement, (SyntaxNode?)rightUsing.Expression ?? rightUsing.Declaration!, rightUsing.Statement); } return true; case SyntaxKind.LockStatement: var leftLock = (LockStatementSyntax)leftNode; var rightLock = (LockStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement); return true; case SyntaxKind.FixedStatement: var leftFixed = (FixedStatementSyntax)leftNode; var rightFixed = (FixedStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement); return true; case SyntaxKind.WhileStatement: var leftWhile = (WhileStatementSyntax)leftNode; var rightWhile = (WhileStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement); return true; case SyntaxKind.DoStatement: var leftDo = (DoStatementSyntax)leftNode; var rightDo = (DoStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement); return true; case SyntaxKind.IfStatement: var leftIf = (IfStatementSyntax)leftNode; var rightIf = (IfStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement); return true; case SyntaxKind.Block: var leftBlock = (BlockSyntax)leftNode; var rightBlock = (BlockSyntax)rightNode; return TryComputeWeightedDistance(leftBlock, rightBlock, out distance); case SyntaxKind.CatchClause: distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode); return true; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: distance = ComputeWeightedDistanceOfNestedFunctions(leftNode, rightNode); return true; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: // Ignore the expression of yield return. The structure of the state machine is more important than the yielded values. distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1; return true; case SyntaxKind.SingleVariableDesignation: distance = ComputeWeightedDistance((SingleVariableDesignationSyntax)leftNode, (SingleVariableDesignationSyntax)rightNode); return true; case SyntaxKind.TypeParameterConstraintClause: distance = ComputeDistance((TypeParameterConstraintClauseSyntax)leftNode, (TypeParameterConstraintClauseSyntax)rightNode); return true; case SyntaxKind.TypeParameter: distance = ComputeDistance((TypeParameterSyntax)leftNode, (TypeParameterSyntax)rightNode); return true; case SyntaxKind.Parameter: distance = ComputeDistance((ParameterSyntax)leftNode, (ParameterSyntax)rightNode); return true; case SyntaxKind.AttributeList: distance = ComputeDistance((AttributeListSyntax)leftNode, (AttributeListSyntax)rightNode); return true; case SyntaxKind.Attribute: distance = ComputeDistance((AttributeSyntax)leftNode, (AttributeSyntax)rightNode); return true; default: var leftName = TryGetName(leftNode); var rightName = TryGetName(rightNode); Contract.ThrowIfFalse(rightName.HasValue == leftName.HasValue); if (leftName.HasValue) { distance = ComputeDistance(leftName.Value, rightName!.Value); return true; } else { distance = 0; return false; } } } private static double ComputeWeightedDistanceOfNestedFunctions(SyntaxNode leftNode, SyntaxNode rightNode) { GetNestedFunctionsParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody, out var leftModifiers, out var leftReturnType, out var leftIdentifier, out var leftTypeParameters); GetNestedFunctionsParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody, out var rightModifiers, out var rightReturnType, out var rightIdentifier, out var rightTypeParameters); if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword)) { return 1.0; } var modifierDistance = ComputeDistance(leftModifiers, rightModifiers); var returnTypeDistance = ComputeDistance(leftReturnType, rightReturnType); var identifierDistance = ComputeDistance(leftIdentifier, rightIdentifier); var typeParameterDistance = ComputeDistance(leftTypeParameters, rightTypeParameters); var parameterDistance = ComputeDistance(leftParameters, rightParameters); var bodyDistance = ComputeDistance(leftBody, rightBody); return modifierDistance * 0.1 + returnTypeDistance * 0.1 + identifierDistance * 0.2 + typeParameterDistance * 0.2 + parameterDistance * 0.2 + bodyDistance * 0.2; } private static void GetNestedFunctionsParts( SyntaxNode nestedFunction, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body, out SyntaxTokenList modifiers, out TypeSyntax? returnType, out SyntaxToken identifier, out TypeParameterListSyntax? typeParameters) { switch (nestedFunction.Kind()) { case SyntaxKind.SimpleLambdaExpression: var simple = (SimpleLambdaExpressionSyntax)nestedFunction; parameters = simple.Parameter.DescendantTokens(); asyncKeyword = simple.AsyncKeyword; body = simple.Body; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.ParenthesizedLambdaExpression: var parenthesized = (ParenthesizedLambdaExpressionSyntax)nestedFunction; parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters); asyncKeyword = parenthesized.AsyncKeyword; body = parenthesized.Body; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.AnonymousMethodExpression: var anonymous = (AnonymousMethodExpressionSyntax)nestedFunction; if (anonymous.ParameterList != null) { parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters); } else { parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>(); } asyncKeyword = anonymous.AsyncKeyword; body = anonymous.Block; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.LocalFunctionStatement: var localFunction = (LocalFunctionStatementSyntax)nestedFunction; parameters = GetDescendantTokensIgnoringSeparators(localFunction.ParameterList.Parameters); asyncKeyword = default; body = (SyntaxNode?)localFunction.Body ?? localFunction.ExpressionBody!; modifiers = localFunction.Modifiers; returnType = localFunction.ReturnType; identifier = localFunction.Identifier; typeParameters = localFunction.TypeParameterList; break; default: throw ExceptionUtilities.UnexpectedValue(nestedFunction.Kind()); } } private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance) { // No block can be matched with the root block. // Note that in constructors the root is the constructor declaration, since we need to include // the constructor initializer in the match. if (leftBlock.Parent == null || rightBlock.Parent == null || leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) || rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { distance = 0.0; return true; } if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent)) { distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; } switch (leftBlock.Parent.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.FixedStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.SwitchSection: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); return true; case SyntaxKind.CatchClause: var leftCatch = (CatchClauseSyntax)leftBlock.Parent; var rightCatch = (CatchClauseSyntax)rightBlock.Parent; if (leftCatch.Declaration == null && leftCatch.Filter == null && rightCatch.Declaration == null && rightCatch.Filter == null) { var leftTry = (TryStatementSyntax)leftCatch.Parent!; var rightTry = (TryStatementSyntax)rightCatch.Parent!; distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) + 0.5 * ComputeValueDistance(leftBlock, rightBlock); } else { // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); } return true; case SyntaxKind.Block: case SyntaxKind.LabeledStatement: distance = ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; case SyntaxKind.UnsafeStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.ElseClause: case SyntaxKind.FinallyClause: case SyntaxKind.TryStatement: distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock); return true; default: throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind()); } } private double ComputeWeightedDistance(SingleVariableDesignationSyntax leftNode, SingleVariableDesignationSyntax rightNode) { var distance = ComputeDistance(leftNode, rightNode); double parentDistance; if (leftNode.Parent != null && rightNode.Parent != null && GetLabel(leftNode.Parent) == GetLabel(rightNode.Parent)) { parentDistance = ComputeDistance(leftNode.Parent, rightNode.Parent); } else { parentDistance = 1; } return 0.5 * parentDistance + 0.5 * distance; } private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock) { if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance)) { return distance; } return ComputeValueDistance(leftBlock, rightBlock); } private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right) { var blockDistance = ComputeDistance(left.Block, right.Block); var distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter); return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3); } private static double ComputeWeightedDistance( CommonForEachStatementSyntax leftCommonForEach, CommonForEachStatementSyntax rightCommonForEach) { var statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement); var expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression); List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; GetLocalNames(leftCommonForEach, ref leftLocals); GetLocalNames(rightCommonForEach, ref rightLocals); var localNamesDistance = ComputeDistance(leftLocals, rightLocals); var distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2; return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6); } private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { var statementDistance = ComputeDistance(left.Statement, right.Statement); var conditionDistance = ComputeDistance(left.Condition, right.Condition); var incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); var distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; } private static double ComputeWeightedDistance( VariableDeclarationSyntax leftVariables, StatementSyntax leftStatement, VariableDeclarationSyntax rightVariables, StatementSyntax rightStatement) { var distance = ComputeDistance(leftStatement, rightStatement); // Put maximum weight behind the variables declared in the header of the statement. if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } // If the statement is a block that declares local variables, // weight them more than the rest of the statement. return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2); } private static double ComputeWeightedDistance( SyntaxNode? leftHeader, StatementSyntax leftStatement, SyntaxNode? rightHeader, StatementSyntax rightStatement) { var headerDistance = ComputeDistance(leftHeader, rightHeader); var statementDistance = ComputeDistance(leftStatement, rightStatement); var distance = headerDistance * 0.6 + statementDistance * 0.4; return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5); } private static double AdjustForLocalsInBlock( double distance, StatementSyntax leftStatement, StatementSyntax rightStatement, double localsWeight) { // If the statement is a block that declares local variables, // weight them more than the rest of the statement. if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block) { if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance)) { return localsDistance * localsWeight + distance * (1 - localsWeight); } } return distance; } private static bool TryComputeLocalsDistance(VariableDeclarationSyntax? left, VariableDeclarationSyntax? right, out double distance) { List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; if (left != null) { GetLocalNames(left, ref leftLocals); } if (right != null) { GetLocalNames(right, ref rightLocals); } if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance) { List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; GetLocalNames(left, ref leftLocals); GetLocalNames(right, ref rightLocals); if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } // Doesn't include variables declared in declaration expressions // Consider including them (https://github.com/dotnet/roslyn/issues/37460). private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken>? result) { foreach (var child in block.ChildNodes()) { if (child.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? localDecl)) { GetLocalNames(localDecl.Declaration, ref result); } } } // Doesn't include variables declared in declaration expressions // Consider including them (https://github.com/dotnet/roslyn/issues/37460). private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken>? result) { foreach (var local in localDeclaration.Variables) { GetLocalNames(local.Identifier, ref result); } } internal static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken>? result) { switch (commonForEach.Kind()) { case SyntaxKind.ForEachStatement: GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result); return; case SyntaxKind.ForEachVariableStatement: var forEachVariable = (ForEachVariableStatementSyntax)commonForEach; GetLocalNames(forEachVariable.Variable, ref result); return; default: throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind()); } } private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken>? result) { switch (expression.Kind()) { case SyntaxKind.DeclarationExpression: var declarationExpression = (DeclarationExpressionSyntax)expression; var localDeclaration = declarationExpression.Designation; GetLocalNames(localDeclaration, ref result); return; case SyntaxKind.TupleExpression: var tupleExpression = (TupleExpressionSyntax)expression; foreach (var argument in tupleExpression.Arguments) { GetLocalNames(argument.Expression, ref result); } return; default: // Do nothing for node that cannot have variable declarations inside. return; } } private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken>? result) { switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result); return; case SyntaxKind.ParenthesizedVariableDesignation: var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation; foreach (var variableDesignation in parenthesizedVariableDesignation.Variables) { GetLocalNames(variableDesignation, ref result); } return; case SyntaxKind.DiscardDesignation: return; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private static void GetLocalNames(SyntaxToken syntaxToken, [NotNull] ref List<SyntaxToken>? result) { result ??= new List<SyntaxToken>(); result.Add(syntaxToken); } private static double CombineOptional( double distance0, SyntaxNode? left1, SyntaxNode? right1, SyntaxNode? left2, SyntaxNode? right2, double weight0 = 0.8, double weight1 = 0.5) { var one = left1 != null || right1 != null; var two = left2 != null || right2 != null; if (!one && !two) { return distance0; } var distance1 = ComputeDistance(left1, right1); var distance2 = ComputeDistance(left2, right2); double d; if (one && two) { d = distance1 * weight1 + distance2 * (1 - weight1); } else if (one) { d = distance1; } else { d = distance2; } return distance0 * weight0 + d * (1 - weight0); } private static SyntaxNodeOrToken? TryGetName(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: return ((ExternAliasDirectiveSyntax)node).Identifier; case SyntaxKind.UsingDirective: return ((UsingDirectiveSyntax)node).Name; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return ((BaseNamespaceDeclarationSyntax)node).Name; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((TypeDeclarationSyntax)node).Identifier; case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)node).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)node).Identifier; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclaration: return null; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)node).Identifier; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)node).Identifier; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)node).Type; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)node).OperatorToken; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)node).Identifier; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)node).Identifier; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)node).Identifier; case SyntaxKind.IndexerDeclaration: return null; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)node).Identifier; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)node).Identifier; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return null; case SyntaxKind.TypeParameterConstraintClause: return ((TypeParameterConstraintClauseSyntax)node).Name.Identifier; case SyntaxKind.TypeParameter: return ((TypeParameterSyntax)node).Identifier; case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: return null; case SyntaxKind.Parameter: return ((ParameterSyntax)node).Identifier; case SyntaxKind.AttributeList: return ((AttributeListSyntax)node).Target; case SyntaxKind.Attribute: return ((AttributeSyntax)node).Name; default: return null; } } public sealed override double GetDistance(SyntaxNode oldNode, SyntaxNode newNode) { Debug.Assert(GetLabel(oldNode) == GetLabel(newNode) && GetLabel(oldNode) != IgnoredNode); if (oldNode == newNode) { return ExactMatchDist; } if (TryComputeWeightedDistance(oldNode, newNode, out var weightedDistance)) { if (weightedDistance == ExactMatchDist && !SyntaxFactory.AreEquivalent(oldNode, newNode)) { weightedDistance = EpsilonDist; } return weightedDistance; } return ComputeValueDistance(oldNode, newNode); } internal static double ComputeValueDistance(SyntaxNode? oldNode, SyntaxNode? newNode) { if (SyntaxFactory.AreEquivalent(oldNode, newNode)) { return ExactMatchDist; } var distance = ComputeDistance(oldNode, newNode); // We don't want to return an exact match, because there // must be something different, since we got here return (distance == ExactMatchDist) ? EpsilonDist : distance; } internal static double ComputeDistance(SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken) { Debug.Assert(newNodeOrToken.IsToken == oldNodeOrToken.IsToken); double distance; if (oldNodeOrToken.IsToken) { var leftToken = oldNodeOrToken.AsToken(); var rightToken = newNodeOrToken.AsToken(); distance = ComputeDistance(leftToken, rightToken); Debug.Assert(!SyntaxFactory.AreEquivalent(leftToken, rightToken) || distance == ExactMatchDist); } else { var leftNode = oldNodeOrToken.AsNode(); var rightNode = newNodeOrToken.AsNode(); distance = ComputeDistance(leftNode, rightNode); Debug.Assert(!SyntaxFactory.AreEquivalent(leftNode, rightNode) || distance == ExactMatchDist); } return distance; } /// <summary> /// Enumerates tokens of all nodes in the list. Doesn't include separators. /// </summary> internal static IEnumerable<SyntaxToken> GetDescendantTokensIgnoringSeparators<TSyntaxNode>(SeparatedSyntaxList<TSyntaxNode> list) where TSyntaxNode : SyntaxNode { foreach (var node in list) { foreach (var token in node.DescendantTokens()) { yield return token; } } } /// <summary> /// Calculates the distance between two syntax nodes, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the nodes are. /// </remarks> public static double ComputeDistance(SyntaxNode? oldNode, SyntaxNode? newNode) { if (oldNode == null || newNode == null) { return (oldNode == newNode) ? 0.0 : 1.0; } return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens()); } /// <summary> /// Calculates the distance between two syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the tokens are. /// </remarks> public static double ComputeDistance(SyntaxToken oldToken, SyntaxToken newToken) => LongestCommonSubstring.ComputeDistance(oldToken.Text, newToken.Text); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens) => LcsTokens.Instance.ComputeDistance(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens) => LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax nodes, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes) => LcsNodes.Instance.ComputeDistance(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => LcsNodes.Instance.ComputeDistance(oldNodes.NullToEmpty(), newNodes.NullToEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes) => LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens) => LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens) => LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty()); private sealed class LcsTokens : LongestCommonImmutableArraySubsequence<SyntaxToken> { internal static readonly LcsTokens Instance = new LcsTokens(); protected override bool Equals(SyntaxToken oldElement, SyntaxToken newElement) => SyntaxFactory.AreEquivalent(oldElement, newElement); } private sealed class LcsNodes : LongestCommonImmutableArraySubsequence<SyntaxNode> { internal static readonly LcsNodes Instance = new LcsNodes(); protected override bool Equals(SyntaxNode oldElement, SyntaxNode newElement) => SyntaxFactory.AreEquivalent(oldElement, newElement); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class SyntaxComparer : AbstractSyntaxComparer { internal static readonly SyntaxComparer TopLevel = new(null, null, null, null, compareStatementSyntax: false); internal static readonly SyntaxComparer Statement = new(null, null, null, null, compareStatementSyntax: true); /// <summary> /// Creates a syntax comparer /// </summary> /// <param name="oldRoot">The root node to start comparisons from</param> /// <param name="newRoot">The new root node to compare against</param> /// <param name="oldRootChildren">Child nodes that should always be compared</param> /// <param name="newRootChildren">New child nodes to compare against</param> /// <param name="compareStatementSyntax">Whether this comparer is in "statement mode"</param> public SyntaxComparer( SyntaxNode? oldRoot, SyntaxNode? newRoot, IEnumerable<SyntaxNode>? oldRootChildren, IEnumerable<SyntaxNode>? newRootChildren, bool compareStatementSyntax) : base(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax) { } protected override bool IsLambdaBodyStatementOrExpression(SyntaxNode node) => LambdaUtilities.IsLambdaBodyStatementOrExpression(node); #region Labels // Assumptions: // - Each listed label corresponds to one or more syntax kinds. // - Nodes with same labels might produce Update edits, nodes with different labels don't. // - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. // (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). // - All descendants of a node whose kind is listed here will be ignored regardless of their labels internal enum Label { // Top level syntax kinds CompilationUnit, GlobalStatement, NamespaceDeclaration, ExternAliasDirective, // tied to parent UsingDirective, // tied to parent TypeDeclaration, EnumDeclaration, DelegateDeclaration, FieldDeclaration, // tied to parent FieldVariableDeclaration, // tied to parent FieldVariableDeclarator, // tied to parent MethodDeclaration, // tied to parent OperatorDeclaration, // tied to parent ConversionOperatorDeclaration, // tied to parent ConstructorDeclaration, // tied to parent DestructorDeclaration, // tied to parent PropertyDeclaration, // tied to parent IndexerDeclaration, // tied to parent EventDeclaration, // tied to parent EnumMemberDeclaration, // tied to parent AccessorList, // tied to parent AccessorDeclaration, // tied to parent // Statement syntax kinds Block, CheckedStatement, UnsafeStatement, TryStatement, CatchClause, // tied to parent CatchDeclaration, // tied to parent CatchFilterClause, // tied to parent FinallyClause, // tied to parent ForStatement, ForStatementPart, // tied to parent ForEachStatement, UsingStatement, FixedStatement, LockStatement, WhileStatement, DoStatement, IfStatement, ElseClause, // tied to parent SwitchStatement, SwitchSection, CasePatternSwitchLabel, // tied to parent SwitchExpression, SwitchExpressionArm, // tied to parent WhenClause, // tied to parent YieldStatement, // tied to parent GotoStatement, GotoCaseStatement, BreakContinueStatement, ReturnThrowStatement, ExpressionStatement, LabeledStatement, // TODO: // Ideally we could declare LocalVariableDeclarator tied to the first enclosing node that defines local scope (block, foreach, etc.) // Also consider handling LocalDeclarationStatement as just a bag of variable declarators, // so that variable declarators contained in one can be matched with variable declarators contained in the other. LocalDeclarationStatement, // tied to parent LocalVariableDeclaration, // tied to parent LocalVariableDeclarator, // tied to parent SingleVariableDesignation, AwaitExpression, NestedFunction, FromClause, QueryBody, FromClauseLambda, // tied to parent LetClauseLambda, // tied to parent WhereClauseLambda, // tied to parent OrderByClause, // tied to parent OrderingLambda, // tied to parent SelectClauseLambda, // tied to parent JoinClauseLambda, // tied to parent JoinIntoClause, // tied to parent GroupClauseLambda, // tied to parent QueryContinuation, // tied to parent // Syntax kinds that are common to both statement and top level TypeParameterList, // tied to parent TypeParameterConstraintClause, // tied to parent TypeParameter, // tied to parent ParameterList, // tied to parent BracketedParameterList, // tied to parent Parameter, // tied to parent AttributeList, // tied to parent Attribute, // tied to parent // helpers: Count, Ignored = IgnoredNode } /// <summary> /// Return 1 if it is desirable to report two edits (delete and insert) rather than a move edit /// when the node changes its parent. /// </summary> private static int TiedToAncestor(Label label) { switch (label) { // Top level syntax case Label.ExternAliasDirective: case Label.UsingDirective: case Label.FieldDeclaration: case Label.FieldVariableDeclaration: case Label.FieldVariableDeclarator: case Label.MethodDeclaration: case Label.OperatorDeclaration: case Label.ConversionOperatorDeclaration: case Label.ConstructorDeclaration: case Label.DestructorDeclaration: case Label.PropertyDeclaration: case Label.IndexerDeclaration: case Label.EventDeclaration: case Label.EnumMemberDeclaration: case Label.AccessorDeclaration: case Label.AccessorList: case Label.TypeParameterList: case Label.TypeParameter: case Label.TypeParameterConstraintClause: case Label.ParameterList: case Label.BracketedParameterList: case Label.Parameter: case Label.AttributeList: case Label.Attribute: return 1; // Statement syntax case Label.LocalDeclarationStatement: case Label.LocalVariableDeclaration: case Label.LocalVariableDeclarator: case Label.GotoCaseStatement: case Label.BreakContinueStatement: case Label.ElseClause: case Label.CatchClause: case Label.CatchDeclaration: case Label.CatchFilterClause: case Label.FinallyClause: case Label.ForStatementPart: case Label.YieldStatement: case Label.FromClauseLambda: case Label.LetClauseLambda: case Label.WhereClauseLambda: case Label.OrderByClause: case Label.OrderingLambda: case Label.SelectClauseLambda: case Label.JoinClauseLambda: case Label.JoinIntoClause: case Label.GroupClauseLambda: case Label.QueryContinuation: case Label.CasePatternSwitchLabel: case Label.WhenClause: case Label.SwitchExpressionArm: return 1; default: return 0; } } internal override int Classify(int kind, SyntaxNode? node, out bool isLeaf) => (int)Classify((SyntaxKind)kind, node, out isLeaf); internal Label Classify(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // If the node is a for loop Initializer, Condition, or Incrementor expression we label it as "ForStatementPart". // We need to capture it in the match since these expressions can be "active statements" and as such we need to map them. // // The parent is not available only when comparing nodes for value equality. if (node != null && node.Parent.IsKind(SyntaxKind.ForStatement) && node is ExpressionSyntax) { return Label.ForStatementPart; } // ************************************ // Top and statement syntax // ************************************ // These nodes can appear during top level and statement processing, so we put them in this first // switch for simplicity. Statement specific, and top level specific cases are handled below. switch (kind) { case SyntaxKind.CompilationUnit: return Label.CompilationUnit; case SyntaxKind.TypeParameterList: return Label.TypeParameterList; case SyntaxKind.TypeParameterConstraintClause: return Label.TypeParameterConstraintClause; case SyntaxKind.TypeParameter: // not a leaf because an attribute may be applied return Label.TypeParameter; case SyntaxKind.BracketedParameterList: return Label.BracketedParameterList; case SyntaxKind.ParameterList: return Label.ParameterList; case SyntaxKind.Parameter: return Label.Parameter; case SyntaxKind.ConstructorDeclaration: // Root when matching constructor bodies. return Label.ConstructorDeclaration; } if (_compareStatementSyntax) { return ClassifyStatementSyntax(kind, node, out isLeaf); } return ClassifyTopSyntax(kind, node, out isLeaf); } private static Label ClassifyStatementSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // ************************************ // Statement syntax // ************************************ // These nodes could potentially be seen as top level syntax, but we only want them labelled // during statement syntax so they have to be kept separate. // // For example when top level sees something like this: // // private int X => new Func(() => { return 1 })(); // // It needs to go through the entire lambda to know if that property def has changed // but if we start labelling things, like ReturnStatement in the above example, then // it will stop. Given that a block bodied lambda can have any statements a user likes // the whole set has to be dealt with separately. switch (kind) { // Notes: // A descendant of a leaf node may be a labeled node that we don't want to visit if // we are comparing its parent node (used for lambda bodies). // // Expressions are ignored but they may contain nodes that should be matched by tree comparer. // (e.g. lambdas, declaration expressions). Descending to these nodes is handled in EnumerateChildren. case SyntaxKind.NamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: // These declarations can come after global statements so we want to stop statement matching // because no global statements can come after them isLeaf = true; return Label.Ignored; case SyntaxKind.LocalDeclarationStatement: return Label.LocalDeclarationStatement; case SyntaxKind.SingleVariableDesignation: return Label.SingleVariableDesignation; case SyntaxKind.LabeledStatement: return Label.LabeledStatement; case SyntaxKind.EmptyStatement: isLeaf = true; return Label.ExpressionStatement; case SyntaxKind.GotoStatement: isLeaf = true; return Label.GotoStatement; case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: isLeaf = true; return Label.GotoCaseStatement; case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: isLeaf = true; return Label.BreakContinueStatement; case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: return Label.ReturnThrowStatement; case SyntaxKind.ExpressionStatement: return Label.ExpressionStatement; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: return Label.YieldStatement; case SyntaxKind.DoStatement: return Label.DoStatement; case SyntaxKind.WhileStatement: return Label.WhileStatement; case SyntaxKind.ForStatement: return Label.ForStatement; case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForEachStatement: return Label.ForEachStatement; case SyntaxKind.UsingStatement: return Label.UsingStatement; case SyntaxKind.FixedStatement: return Label.FixedStatement; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return Label.CheckedStatement; case SyntaxKind.UnsafeStatement: return Label.UnsafeStatement; case SyntaxKind.LockStatement: return Label.LockStatement; case SyntaxKind.IfStatement: return Label.IfStatement; case SyntaxKind.ElseClause: return Label.ElseClause; case SyntaxKind.SwitchStatement: return Label.SwitchStatement; case SyntaxKind.SwitchSection: return Label.SwitchSection; case SyntaxKind.CaseSwitchLabel: case SyntaxKind.DefaultSwitchLabel: // Switch labels are included in the "value" of the containing switch section. // We don't need to analyze case expressions. isLeaf = true; return Label.Ignored; case SyntaxKind.WhenClause: return Label.WhenClause; case SyntaxKind.CasePatternSwitchLabel: return Label.CasePatternSwitchLabel; case SyntaxKind.SwitchExpression: return Label.SwitchExpression; case SyntaxKind.SwitchExpressionArm: return Label.SwitchExpressionArm; case SyntaxKind.TryStatement: return Label.TryStatement; case SyntaxKind.CatchClause: return Label.CatchClause; case SyntaxKind.CatchDeclaration: // the declarator of the exception variable return Label.CatchDeclaration; case SyntaxKind.CatchFilterClause: return Label.CatchFilterClause; case SyntaxKind.FinallyClause: return Label.FinallyClause; case SyntaxKind.FromClause: // The first from clause of a query is not a lambda. // We have to assign it a label different from "FromClauseLambda" // so that we won't match lambda-from to non-lambda-from. // // Since FromClause declares range variables we need to include it in the map, // so that we are able to map range variable declarations. // Therefore we assign it a dedicated label. // // The parent is not available only when comparing nodes for value equality. // In that case it doesn't matter what label the node has as long as it has some. if (node == null || node.Parent.IsKind(SyntaxKind.QueryExpression)) { return Label.FromClause; } return Label.FromClauseLambda; case SyntaxKind.QueryBody: return Label.QueryBody; case SyntaxKind.QueryContinuation: return Label.QueryContinuation; case SyntaxKind.LetClause: return Label.LetClauseLambda; case SyntaxKind.WhereClause: return Label.WhereClauseLambda; case SyntaxKind.OrderByClause: return Label.OrderByClause; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return Label.OrderingLambda; case SyntaxKind.SelectClause: return Label.SelectClauseLambda; case SyntaxKind.JoinClause: return Label.JoinClauseLambda; case SyntaxKind.JoinIntoClause: return Label.JoinIntoClause; case SyntaxKind.GroupClause: return Label.GroupClauseLambda; case SyntaxKind.IdentifierName: case SyntaxKind.QualifiedName: case SyntaxKind.GenericName: case SyntaxKind.TypeArgumentList: case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: case SyntaxKind.PointerType: case SyntaxKind.NullableType: case SyntaxKind.TupleType: case SyntaxKind.RefType: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.NameColon: case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.ArgListExpression: case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: case SyntaxKind.TypeOfExpression: case SyntaxKind.SizeOfExpression: case SyntaxKind.DefaultExpression: case SyntaxKind.ConstantPattern: case SyntaxKind.DiscardDesignation: // can't contain a lambda/await/anonymous type: isLeaf = true; return Label.Ignored; case SyntaxKind.AwaitExpression: return Label.AwaitExpression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: return Label.NestedFunction; case SyntaxKind.VariableDeclaration: return Label.LocalVariableDeclaration; case SyntaxKind.VariableDeclarator: return Label.LocalVariableDeclarator; case SyntaxKind.Block: return Label.Block; } // If we got this far, its an unlabelled node. Since just about any node can // contain a lambda, isLeaf must be false for statement syntax. return Label.Ignored; } private static Label ClassifyTopSyntax(SyntaxKind kind, SyntaxNode? node, out bool isLeaf) { isLeaf = false; // ************************************ // Top syntax // ************************************ // More the most part these nodes will only appear in top syntax but its easier to // keep them separate so we can more easily discern was is shared, above. switch (kind) { case SyntaxKind.GlobalStatement: isLeaf = true; return Label.GlobalStatement; case SyntaxKind.ExternAliasDirective: isLeaf = true; return Label.ExternAliasDirective; case SyntaxKind.UsingDirective: isLeaf = true; return Label.UsingDirective; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Label.NamespaceDeclaration; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return Label.TypeDeclaration; case SyntaxKind.MethodDeclaration: return Label.MethodDeclaration; case SyntaxKind.EnumDeclaration: return Label.EnumDeclaration; case SyntaxKind.DelegateDeclaration: return Label.DelegateDeclaration; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return Label.FieldDeclaration; case SyntaxKind.ConversionOperatorDeclaration: return Label.ConversionOperatorDeclaration; case SyntaxKind.OperatorDeclaration: return Label.OperatorDeclaration; case SyntaxKind.DestructorDeclaration: isLeaf = true; return Label.DestructorDeclaration; case SyntaxKind.PropertyDeclaration: return Label.PropertyDeclaration; case SyntaxKind.IndexerDeclaration: return Label.IndexerDeclaration; case SyntaxKind.EventDeclaration: return Label.EventDeclaration; case SyntaxKind.EnumMemberDeclaration: // not a leaf because an attribute may be applied return Label.EnumMemberDeclaration; case SyntaxKind.AccessorList: return Label.AccessorList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: isLeaf = true; return Label.AccessorDeclaration; // Note: These last two do actually appear as statement syntax, but mean something // different and hence have a different label case SyntaxKind.VariableDeclaration: return Label.FieldVariableDeclaration; case SyntaxKind.VariableDeclarator: // For top syntax, a variable declarator is a leaf node isLeaf = true; return Label.FieldVariableDeclarator; case SyntaxKind.AttributeList: // Only module/assembly attributes are labelled if (node is not null && node.IsParentKind(SyntaxKind.CompilationUnit)) { return Label.AttributeList; } break; case SyntaxKind.Attribute: // Only module/assembly attributes are labelled if (node is { Parent: { } parent } && parent.IsParentKind(SyntaxKind.CompilationUnit)) { isLeaf = true; return Label.Attribute; } break; } // If we got this far, its an unlabelled node. For top // syntax, we don't need to descend into any ignored nodes isLeaf = true; return Label.Ignored; } // internal for testing internal bool HasLabel(SyntaxKind kind) => Classify(kind, node: null, out _) != Label.Ignored; protected internal override int LabelCount => (int)Label.Count; protected internal override int TiedToAncestor(int label) => TiedToAncestor((Label)label); #endregion #region Comparisons public override bool ValuesEqual(SyntaxNode left, SyntaxNode right) { Func<SyntaxKind, bool>? ignoreChildFunction; switch (left.Kind()) { // all syntax kinds with a method body child: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: // When comparing method bodies we need to NOT ignore VariableDeclaration and VariableDeclarator children, // but when comparing field definitions we should ignore VariableDeclarations children. var leftBody = GetBody(left); var rightBody = GetBody(right); if (!SyntaxFactory.AreEquivalent(leftBody, rightBody, null)) { return false; } ignoreChildFunction = childKind => childKind == SyntaxKind.Block || childKind == SyntaxKind.ArrowExpressionClause || HasLabel(childKind); break; case SyntaxKind.SwitchSection: return Equal((SwitchSectionSyntax)left, (SwitchSectionSyntax)right); case SyntaxKind.ForStatement: // The only children of ForStatement are labeled nodes and punctuation. return true; default: if (HasChildren(left)) { ignoreChildFunction = childKind => HasLabel(childKind); } else { ignoreChildFunction = null; } break; } return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction); } private bool Equal(SwitchSectionSyntax left, SwitchSectionSyntax right) { return SyntaxFactory.AreEquivalent(left.Labels, right.Labels, null) && SyntaxFactory.AreEquivalent(left.Statements, right.Statements, ignoreChildNode: HasLabel); } private static SyntaxNode? GetBody(SyntaxNode node) { switch (node) { case BaseMethodDeclarationSyntax baseMethodDeclarationSyntax: return baseMethodDeclarationSyntax.Body ?? (SyntaxNode?)baseMethodDeclarationSyntax.ExpressionBody?.Expression; case AccessorDeclarationSyntax accessorDeclarationSyntax: return accessorDeclarationSyntax.Body ?? (SyntaxNode?)accessorDeclarationSyntax.ExpressionBody?.Expression; default: throw ExceptionUtilities.UnexpectedValue(node); } } protected override bool TryComputeWeightedDistance(SyntaxNode leftNode, SyntaxNode rightNode, out double distance) { switch (leftNode.Kind()) { case SyntaxKind.VariableDeclarator: distance = ComputeDistance( ((VariableDeclaratorSyntax)leftNode).Identifier, ((VariableDeclaratorSyntax)rightNode).Identifier); return true; case SyntaxKind.ForStatement: var leftFor = (ForStatementSyntax)leftNode; var rightFor = (ForStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFor, rightFor); return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: { var leftForEach = (CommonForEachStatementSyntax)leftNode; var rightForEach = (CommonForEachStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftForEach, rightForEach); return true; } case SyntaxKind.UsingStatement: var leftUsing = (UsingStatementSyntax)leftNode; var rightUsing = (UsingStatementSyntax)rightNode; if (leftUsing.Declaration != null && rightUsing.Declaration != null) { distance = ComputeWeightedDistance( leftUsing.Declaration, leftUsing.Statement, rightUsing.Declaration, rightUsing.Statement); } else { distance = ComputeWeightedDistance( (SyntaxNode?)leftUsing.Expression ?? leftUsing.Declaration!, leftUsing.Statement, (SyntaxNode?)rightUsing.Expression ?? rightUsing.Declaration!, rightUsing.Statement); } return true; case SyntaxKind.LockStatement: var leftLock = (LockStatementSyntax)leftNode; var rightLock = (LockStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftLock.Expression, leftLock.Statement, rightLock.Expression, rightLock.Statement); return true; case SyntaxKind.FixedStatement: var leftFixed = (FixedStatementSyntax)leftNode; var rightFixed = (FixedStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftFixed.Declaration, leftFixed.Statement, rightFixed.Declaration, rightFixed.Statement); return true; case SyntaxKind.WhileStatement: var leftWhile = (WhileStatementSyntax)leftNode; var rightWhile = (WhileStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftWhile.Condition, leftWhile.Statement, rightWhile.Condition, rightWhile.Statement); return true; case SyntaxKind.DoStatement: var leftDo = (DoStatementSyntax)leftNode; var rightDo = (DoStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftDo.Condition, leftDo.Statement, rightDo.Condition, rightDo.Statement); return true; case SyntaxKind.IfStatement: var leftIf = (IfStatementSyntax)leftNode; var rightIf = (IfStatementSyntax)rightNode; distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statement, rightIf.Condition, rightIf.Statement); return true; case SyntaxKind.Block: var leftBlock = (BlockSyntax)leftNode; var rightBlock = (BlockSyntax)rightNode; return TryComputeWeightedDistance(leftBlock, rightBlock, out distance); case SyntaxKind.CatchClause: distance = ComputeWeightedDistance((CatchClauseSyntax)leftNode, (CatchClauseSyntax)rightNode); return true; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: distance = ComputeWeightedDistanceOfNestedFunctions(leftNode, rightNode); return true; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: // Ignore the expression of yield return. The structure of the state machine is more important than the yielded values. distance = (leftNode.RawKind == rightNode.RawKind) ? 0.0 : 0.1; return true; case SyntaxKind.SingleVariableDesignation: distance = ComputeWeightedDistance((SingleVariableDesignationSyntax)leftNode, (SingleVariableDesignationSyntax)rightNode); return true; case SyntaxKind.TypeParameterConstraintClause: distance = ComputeDistance((TypeParameterConstraintClauseSyntax)leftNode, (TypeParameterConstraintClauseSyntax)rightNode); return true; case SyntaxKind.TypeParameter: distance = ComputeDistance((TypeParameterSyntax)leftNode, (TypeParameterSyntax)rightNode); return true; case SyntaxKind.Parameter: distance = ComputeDistance((ParameterSyntax)leftNode, (ParameterSyntax)rightNode); return true; case SyntaxKind.AttributeList: distance = ComputeDistance((AttributeListSyntax)leftNode, (AttributeListSyntax)rightNode); return true; case SyntaxKind.Attribute: distance = ComputeDistance((AttributeSyntax)leftNode, (AttributeSyntax)rightNode); return true; default: var leftName = TryGetName(leftNode); var rightName = TryGetName(rightNode); Contract.ThrowIfFalse(rightName.HasValue == leftName.HasValue); if (leftName.HasValue) { distance = ComputeDistance(leftName.Value, rightName!.Value); return true; } else { distance = 0; return false; } } } private static double ComputeWeightedDistanceOfNestedFunctions(SyntaxNode leftNode, SyntaxNode rightNode) { GetNestedFunctionsParts(leftNode, out var leftParameters, out var leftAsync, out var leftBody, out var leftModifiers, out var leftReturnType, out var leftIdentifier, out var leftTypeParameters); GetNestedFunctionsParts(rightNode, out var rightParameters, out var rightAsync, out var rightBody, out var rightModifiers, out var rightReturnType, out var rightIdentifier, out var rightTypeParameters); if ((leftAsync.Kind() == SyntaxKind.AsyncKeyword) != (rightAsync.Kind() == SyntaxKind.AsyncKeyword)) { return 1.0; } var modifierDistance = ComputeDistance(leftModifiers, rightModifiers); var returnTypeDistance = ComputeDistance(leftReturnType, rightReturnType); var identifierDistance = ComputeDistance(leftIdentifier, rightIdentifier); var typeParameterDistance = ComputeDistance(leftTypeParameters, rightTypeParameters); var parameterDistance = ComputeDistance(leftParameters, rightParameters); var bodyDistance = ComputeDistance(leftBody, rightBody); return modifierDistance * 0.1 + returnTypeDistance * 0.1 + identifierDistance * 0.2 + typeParameterDistance * 0.2 + parameterDistance * 0.2 + bodyDistance * 0.2; } private static void GetNestedFunctionsParts( SyntaxNode nestedFunction, out IEnumerable<SyntaxToken> parameters, out SyntaxToken asyncKeyword, out SyntaxNode body, out SyntaxTokenList modifiers, out TypeSyntax? returnType, out SyntaxToken identifier, out TypeParameterListSyntax? typeParameters) { switch (nestedFunction.Kind()) { case SyntaxKind.SimpleLambdaExpression: var simple = (SimpleLambdaExpressionSyntax)nestedFunction; parameters = simple.Parameter.DescendantTokens(); asyncKeyword = simple.AsyncKeyword; body = simple.Body; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.ParenthesizedLambdaExpression: var parenthesized = (ParenthesizedLambdaExpressionSyntax)nestedFunction; parameters = GetDescendantTokensIgnoringSeparators(parenthesized.ParameterList.Parameters); asyncKeyword = parenthesized.AsyncKeyword; body = parenthesized.Body; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.AnonymousMethodExpression: var anonymous = (AnonymousMethodExpressionSyntax)nestedFunction; if (anonymous.ParameterList != null) { parameters = GetDescendantTokensIgnoringSeparators(anonymous.ParameterList.Parameters); } else { parameters = SpecializedCollections.EmptyEnumerable<SyntaxToken>(); } asyncKeyword = anonymous.AsyncKeyword; body = anonymous.Block; modifiers = default; returnType = null; identifier = default; typeParameters = null; break; case SyntaxKind.LocalFunctionStatement: var localFunction = (LocalFunctionStatementSyntax)nestedFunction; parameters = GetDescendantTokensIgnoringSeparators(localFunction.ParameterList.Parameters); asyncKeyword = default; body = (SyntaxNode?)localFunction.Body ?? localFunction.ExpressionBody!; modifiers = localFunction.Modifiers; returnType = localFunction.ReturnType; identifier = localFunction.Identifier; typeParameters = localFunction.TypeParameterList; break; default: throw ExceptionUtilities.UnexpectedValue(nestedFunction.Kind()); } } private bool TryComputeWeightedDistance(BlockSyntax leftBlock, BlockSyntax rightBlock, out double distance) { // No block can be matched with the root block. // Note that in constructors the root is the constructor declaration, since we need to include // the constructor initializer in the match. if (leftBlock.Parent == null || rightBlock.Parent == null || leftBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration) || rightBlock.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { distance = 0.0; return true; } if (GetLabel(leftBlock.Parent) != GetLabel(rightBlock.Parent)) { distance = 0.2 + 0.8 * ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; } switch (leftBlock.Parent.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.ForStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.FixedStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.SwitchSection: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.LocalFunctionStatement: // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); return true; case SyntaxKind.CatchClause: var leftCatch = (CatchClauseSyntax)leftBlock.Parent; var rightCatch = (CatchClauseSyntax)rightBlock.Parent; if (leftCatch.Declaration == null && leftCatch.Filter == null && rightCatch.Declaration == null && rightCatch.Filter == null) { var leftTry = (TryStatementSyntax)leftCatch.Parent!; var rightTry = (TryStatementSyntax)rightCatch.Parent!; distance = 0.5 * ComputeValueDistance(leftTry.Block, rightTry.Block) + 0.5 * ComputeValueDistance(leftBlock, rightBlock); } else { // value distance of the block body is included: distance = GetDistance(leftBlock.Parent, rightBlock.Parent); } return true; case SyntaxKind.Block: case SyntaxKind.LabeledStatement: distance = ComputeWeightedBlockDistance(leftBlock, rightBlock); return true; case SyntaxKind.UnsafeStatement: case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: case SyntaxKind.ElseClause: case SyntaxKind.FinallyClause: case SyntaxKind.TryStatement: distance = 0.2 * ComputeValueDistance(leftBlock, rightBlock); return true; default: throw ExceptionUtilities.UnexpectedValue(leftBlock.Parent.Kind()); } } private double ComputeWeightedDistance(SingleVariableDesignationSyntax leftNode, SingleVariableDesignationSyntax rightNode) { var distance = ComputeDistance(leftNode, rightNode); double parentDistance; if (leftNode.Parent != null && rightNode.Parent != null && GetLabel(leftNode.Parent) == GetLabel(rightNode.Parent)) { parentDistance = ComputeDistance(leftNode.Parent, rightNode.Parent); } else { parentDistance = 1; } return 0.5 * parentDistance + 0.5 * distance; } private static double ComputeWeightedBlockDistance(BlockSyntax leftBlock, BlockSyntax rightBlock) { if (TryComputeLocalsDistance(leftBlock, rightBlock, out var distance)) { return distance; } return ComputeValueDistance(leftBlock, rightBlock); } private static double ComputeWeightedDistance(CatchClauseSyntax left, CatchClauseSyntax right) { var blockDistance = ComputeDistance(left.Block, right.Block); var distance = CombineOptional(blockDistance, left.Declaration, right.Declaration, left.Filter, right.Filter); return AdjustForLocalsInBlock(distance, left.Block, right.Block, localsWeight: 0.3); } private static double ComputeWeightedDistance( CommonForEachStatementSyntax leftCommonForEach, CommonForEachStatementSyntax rightCommonForEach) { var statementDistance = ComputeDistance(leftCommonForEach.Statement, rightCommonForEach.Statement); var expressionDistance = ComputeDistance(leftCommonForEach.Expression, rightCommonForEach.Expression); List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; GetLocalNames(leftCommonForEach, ref leftLocals); GetLocalNames(rightCommonForEach, ref rightLocals); var localNamesDistance = ComputeDistance(leftLocals, rightLocals); var distance = localNamesDistance * 0.6 + expressionDistance * 0.2 + statementDistance * 0.2; return AdjustForLocalsInBlock(distance, leftCommonForEach.Statement, rightCommonForEach.Statement, localsWeight: 0.6); } private static double ComputeWeightedDistance(ForStatementSyntax left, ForStatementSyntax right) { var statementDistance = ComputeDistance(left.Statement, right.Statement); var conditionDistance = ComputeDistance(left.Condition, right.Condition); var incDistance = ComputeDistance( GetDescendantTokensIgnoringSeparators(left.Incrementors), GetDescendantTokensIgnoringSeparators(right.Incrementors)); var distance = conditionDistance * 0.3 + incDistance * 0.3 + statementDistance * 0.4; if (TryComputeLocalsDistance(left.Declaration, right.Declaration, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } return distance; } private static double ComputeWeightedDistance( VariableDeclarationSyntax leftVariables, StatementSyntax leftStatement, VariableDeclarationSyntax rightVariables, StatementSyntax rightStatement) { var distance = ComputeDistance(leftStatement, rightStatement); // Put maximum weight behind the variables declared in the header of the statement. if (TryComputeLocalsDistance(leftVariables, rightVariables, out var localsDistance)) { distance = distance * 0.4 + localsDistance * 0.6; } // If the statement is a block that declares local variables, // weight them more than the rest of the statement. return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.2); } private static double ComputeWeightedDistance( SyntaxNode? leftHeader, StatementSyntax leftStatement, SyntaxNode? rightHeader, StatementSyntax rightStatement) { var headerDistance = ComputeDistance(leftHeader, rightHeader); var statementDistance = ComputeDistance(leftStatement, rightStatement); var distance = headerDistance * 0.6 + statementDistance * 0.4; return AdjustForLocalsInBlock(distance, leftStatement, rightStatement, localsWeight: 0.5); } private static double AdjustForLocalsInBlock( double distance, StatementSyntax leftStatement, StatementSyntax rightStatement, double localsWeight) { // If the statement is a block that declares local variables, // weight them more than the rest of the statement. if (leftStatement.Kind() == SyntaxKind.Block && rightStatement.Kind() == SyntaxKind.Block) { if (TryComputeLocalsDistance((BlockSyntax)leftStatement, (BlockSyntax)rightStatement, out var localsDistance)) { return localsDistance * localsWeight + distance * (1 - localsWeight); } } return distance; } private static bool TryComputeLocalsDistance(VariableDeclarationSyntax? left, VariableDeclarationSyntax? right, out double distance) { List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; if (left != null) { GetLocalNames(left, ref leftLocals); } if (right != null) { GetLocalNames(right, ref rightLocals); } if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } private static bool TryComputeLocalsDistance(BlockSyntax left, BlockSyntax right, out double distance) { List<SyntaxToken>? leftLocals = null; List<SyntaxToken>? rightLocals = null; GetLocalNames(left, ref leftLocals); GetLocalNames(right, ref rightLocals); if (leftLocals == null || rightLocals == null) { distance = 0; return false; } distance = ComputeDistance(leftLocals, rightLocals); return true; } // Doesn't include variables declared in declaration expressions // Consider including them (https://github.com/dotnet/roslyn/issues/37460). private static void GetLocalNames(BlockSyntax block, ref List<SyntaxToken>? result) { foreach (var child in block.ChildNodes()) { if (child.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax? localDecl)) { GetLocalNames(localDecl.Declaration, ref result); } } } // Doesn't include variables declared in declaration expressions // Consider including them (https://github.com/dotnet/roslyn/issues/37460). private static void GetLocalNames(VariableDeclarationSyntax localDeclaration, ref List<SyntaxToken>? result) { foreach (var local in localDeclaration.Variables) { GetLocalNames(local.Identifier, ref result); } } internal static void GetLocalNames(CommonForEachStatementSyntax commonForEach, ref List<SyntaxToken>? result) { switch (commonForEach.Kind()) { case SyntaxKind.ForEachStatement: GetLocalNames(((ForEachStatementSyntax)commonForEach).Identifier, ref result); return; case SyntaxKind.ForEachVariableStatement: var forEachVariable = (ForEachVariableStatementSyntax)commonForEach; GetLocalNames(forEachVariable.Variable, ref result); return; default: throw ExceptionUtilities.UnexpectedValue(commonForEach.Kind()); } } private static void GetLocalNames(ExpressionSyntax expression, ref List<SyntaxToken>? result) { switch (expression.Kind()) { case SyntaxKind.DeclarationExpression: var declarationExpression = (DeclarationExpressionSyntax)expression; var localDeclaration = declarationExpression.Designation; GetLocalNames(localDeclaration, ref result); return; case SyntaxKind.TupleExpression: var tupleExpression = (TupleExpressionSyntax)expression; foreach (var argument in tupleExpression.Arguments) { GetLocalNames(argument.Expression, ref result); } return; default: // Do nothing for node that cannot have variable declarations inside. return; } } private static void GetLocalNames(VariableDesignationSyntax designation, ref List<SyntaxToken>? result) { switch (designation.Kind()) { case SyntaxKind.SingleVariableDesignation: GetLocalNames(((SingleVariableDesignationSyntax)designation).Identifier, ref result); return; case SyntaxKind.ParenthesizedVariableDesignation: var parenthesizedVariableDesignation = (ParenthesizedVariableDesignationSyntax)designation; foreach (var variableDesignation in parenthesizedVariableDesignation.Variables) { GetLocalNames(variableDesignation, ref result); } return; case SyntaxKind.DiscardDesignation: return; default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private static void GetLocalNames(SyntaxToken syntaxToken, [NotNull] ref List<SyntaxToken>? result) { result ??= new List<SyntaxToken>(); result.Add(syntaxToken); } private static double CombineOptional( double distance0, SyntaxNode? left1, SyntaxNode? right1, SyntaxNode? left2, SyntaxNode? right2, double weight0 = 0.8, double weight1 = 0.5) { var one = left1 != null || right1 != null; var two = left2 != null || right2 != null; if (!one && !two) { return distance0; } var distance1 = ComputeDistance(left1, right1); var distance2 = ComputeDistance(left2, right2); double d; if (one && two) { d = distance1 * weight1 + distance2 * (1 - weight1); } else if (one) { d = distance1; } else { d = distance2; } return distance0 * weight0 + d * (1 - weight0); } private static SyntaxNodeOrToken? TryGetName(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: return ((ExternAliasDirectiveSyntax)node).Identifier; case SyntaxKind.UsingDirective: return ((UsingDirectiveSyntax)node).Name; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return ((BaseNamespaceDeclarationSyntax)node).Name; case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((TypeDeclarationSyntax)node).Identifier; case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)node).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)node).Identifier; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclaration: return null; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)node).Identifier; case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)node).Identifier; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)node).Type; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)node).OperatorToken; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)node).Identifier; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)node).Identifier; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)node).Identifier; case SyntaxKind.IndexerDeclaration: return null; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)node).Identifier; case SyntaxKind.EnumMemberDeclaration: return ((EnumMemberDeclarationSyntax)node).Identifier; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return null; case SyntaxKind.TypeParameterConstraintClause: return ((TypeParameterConstraintClauseSyntax)node).Name.Identifier; case SyntaxKind.TypeParameter: return ((TypeParameterSyntax)node).Identifier; case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: return null; case SyntaxKind.Parameter: return ((ParameterSyntax)node).Identifier; case SyntaxKind.AttributeList: return ((AttributeListSyntax)node).Target; case SyntaxKind.Attribute: return ((AttributeSyntax)node).Name; default: return null; } } public sealed override double GetDistance(SyntaxNode oldNode, SyntaxNode newNode) { Debug.Assert(GetLabel(oldNode) == GetLabel(newNode) && GetLabel(oldNode) != IgnoredNode); if (oldNode == newNode) { return ExactMatchDist; } if (TryComputeWeightedDistance(oldNode, newNode, out var weightedDistance)) { if (weightedDistance == ExactMatchDist && !SyntaxFactory.AreEquivalent(oldNode, newNode)) { weightedDistance = EpsilonDist; } return weightedDistance; } return ComputeValueDistance(oldNode, newNode); } internal static double ComputeValueDistance(SyntaxNode? oldNode, SyntaxNode? newNode) { if (SyntaxFactory.AreEquivalent(oldNode, newNode)) { return ExactMatchDist; } var distance = ComputeDistance(oldNode, newNode); // We don't want to return an exact match, because there // must be something different, since we got here return (distance == ExactMatchDist) ? EpsilonDist : distance; } internal static double ComputeDistance(SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken) { Debug.Assert(newNodeOrToken.IsToken == oldNodeOrToken.IsToken); double distance; if (oldNodeOrToken.IsToken) { var leftToken = oldNodeOrToken.AsToken(); var rightToken = newNodeOrToken.AsToken(); distance = ComputeDistance(leftToken, rightToken); Debug.Assert(!SyntaxFactory.AreEquivalent(leftToken, rightToken) || distance == ExactMatchDist); } else { var leftNode = oldNodeOrToken.AsNode(); var rightNode = newNodeOrToken.AsNode(); distance = ComputeDistance(leftNode, rightNode); Debug.Assert(!SyntaxFactory.AreEquivalent(leftNode, rightNode) || distance == ExactMatchDist); } return distance; } /// <summary> /// Enumerates tokens of all nodes in the list. Doesn't include separators. /// </summary> internal static IEnumerable<SyntaxToken> GetDescendantTokensIgnoringSeparators<TSyntaxNode>(SeparatedSyntaxList<TSyntaxNode> list) where TSyntaxNode : SyntaxNode { foreach (var node in list) { foreach (var token in node.DescendantTokens()) { yield return token; } } } /// <summary> /// Calculates the distance between two syntax nodes, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the nodes are. /// </remarks> public static double ComputeDistance(SyntaxNode? oldNode, SyntaxNode? newNode) { if (oldNode == null || newNode == null) { return (oldNode == newNode) ? 0.0 : 1.0; } return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens()); } /// <summary> /// Calculates the distance between two syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the tokens are. /// </remarks> public static double ComputeDistance(SyntaxToken oldToken, SyntaxToken newToken) => LongestCommonSubstring.ComputeDistance(oldToken.Text, newToken.Text); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens) => LcsTokens.Instance.ComputeDistance(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens) => LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax nodes, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes) => LcsNodes.Instance.ComputeDistance(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()); /// <summary> /// Calculates the distance between two sequences of syntax tokens, disregarding trivia. /// </summary> /// <remarks> /// Distance is a number within [0, 1], the smaller the more similar the sequences are. /// </remarks> public static double ComputeDistance(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => LcsNodes.Instance.ComputeDistance(oldNodes.NullToEmpty(), newNodes.NullToEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxNode>? oldNodes, IEnumerable<SyntaxNode>? newNodes) => LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(IEnumerable<SyntaxToken>? oldTokens, IEnumerable<SyntaxToken>? newTokens) => LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()); /// <summary> /// Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. /// </summary> public static IEnumerable<SequenceEdit> GetSequenceEdits(ImmutableArray<SyntaxToken> oldTokens, ImmutableArray<SyntaxToken> newTokens) => LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty()); private sealed class LcsTokens : LongestCommonImmutableArraySubsequence<SyntaxToken> { internal static readonly LcsTokens Instance = new LcsTokens(); protected override bool Equals(SyntaxToken oldElement, SyntaxToken newElement) => SyntaxFactory.AreEquivalent(oldElement, newElement); } private sealed class LcsNodes : LongestCommonImmutableArraySubsequence<SyntaxNode> { internal static readonly LcsNodes Instance = new LcsNodes(); protected override bool Equals(SyntaxNode oldElement, SyntaxNode newElement) => SyntaxFactory.AreEquivalent(oldElement, newElement); } #endregion } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/EditorConfig/EditorConfigNamingStyleParser_NamingStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetNamingStyleData( string namingRuleName, IReadOnlyDictionary<string, string> rawOptions, out NamingStyle namingStyle) { namingStyle = default; if (!TryGetNamingStyleTitle(namingRuleName, rawOptions, out var namingStyleTitle)) { return false; } var requiredPrefix = GetNamingRequiredPrefix(namingStyleTitle, rawOptions); var requiredSuffix = GetNamingRequiredSuffix(namingStyleTitle, rawOptions); var wordSeparator = GetNamingWordSeparator(namingStyleTitle, rawOptions); if (!TryGetNamingCapitalization(namingStyleTitle, rawOptions, out var capitalization)) { return false; } namingStyle = new NamingStyle( Guid.NewGuid(), name: namingStyleTitle, prefix: requiredPrefix, suffix: requiredSuffix, wordSeparator: wordSeparator, capitalizationScheme: capitalization); return true; } private static bool TryGetNamingStyleTitle( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out string namingStyleName) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.style", out namingStyleName)) { return namingStyleName != null; } namingStyleName = null; return false; } private static string GetNamingRequiredPrefix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_prefix", conventionsDictionary); private static string GetNamingRequiredSuffix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_suffix", conventionsDictionary); private static string GetNamingWordSeparator(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "word_separator", conventionsDictionary); private static bool TryGetNamingCapitalization(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary, out Capitalization capitalization) { var result = GetStringFromConventionsDictionary(namingStyleName, "capitalization", conventionsDictionary); return TryParseCapitalizationScheme(result, out capitalization); } private static string GetStringFromConventionsDictionary(string namingStyleName, string optionName, IReadOnlyDictionary<string, string> conventionsDictionary) { conventionsDictionary.TryGetValue($"dotnet_naming_style.{namingStyleName}.{optionName}", out var result); return result ?? string.Empty; } private static bool TryParseCapitalizationScheme(string namingStyleCapitalization, out Capitalization capitalization) { switch (namingStyleCapitalization) { case "pascal_case": capitalization = Capitalization.PascalCase; return true; case "camel_case": capitalization = Capitalization.CamelCase; return true; case "first_word_upper": capitalization = Capitalization.FirstUpper; return true; case "all_upper": capitalization = Capitalization.AllUpper; return true; case "all_lower": capitalization = Capitalization.AllLower; return true; default: capitalization = default; return false; } } public static string ToEditorConfigString(this Capitalization capitalization) { switch (capitalization) { case Capitalization.PascalCase: return "pascal_case"; case Capitalization.CamelCase: return "camel_case"; case Capitalization.FirstUpper: return "first_word_upper"; case Capitalization.AllUpper: return "all_upper"; case Capitalization.AllLower: return "all_lower"; default: throw ExceptionUtilities.UnexpectedValue(capitalization); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Microsoft.CodeAnalysis.NamingStyles; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal static partial class EditorConfigNamingStyleParser { private static bool TryGetNamingStyleData( string namingRuleName, IReadOnlyDictionary<string, string> rawOptions, out NamingStyle namingStyle) { namingStyle = default; if (!TryGetNamingStyleTitle(namingRuleName, rawOptions, out var namingStyleTitle)) { return false; } var requiredPrefix = GetNamingRequiredPrefix(namingStyleTitle, rawOptions); var requiredSuffix = GetNamingRequiredSuffix(namingStyleTitle, rawOptions); var wordSeparator = GetNamingWordSeparator(namingStyleTitle, rawOptions); if (!TryGetNamingCapitalization(namingStyleTitle, rawOptions, out var capitalization)) { return false; } namingStyle = new NamingStyle( Guid.NewGuid(), name: namingStyleTitle, prefix: requiredPrefix, suffix: requiredSuffix, wordSeparator: wordSeparator, capitalizationScheme: capitalization); return true; } private static bool TryGetNamingStyleTitle( string namingRuleName, IReadOnlyDictionary<string, string> conventionsDictionary, out string namingStyleName) { if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.style", out namingStyleName)) { return namingStyleName != null; } namingStyleName = null; return false; } private static string GetNamingRequiredPrefix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_prefix", conventionsDictionary); private static string GetNamingRequiredSuffix(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "required_suffix", conventionsDictionary); private static string GetNamingWordSeparator(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary) => GetStringFromConventionsDictionary(namingStyleName, "word_separator", conventionsDictionary); private static bool TryGetNamingCapitalization(string namingStyleName, IReadOnlyDictionary<string, string> conventionsDictionary, out Capitalization capitalization) { var result = GetStringFromConventionsDictionary(namingStyleName, "capitalization", conventionsDictionary); return TryParseCapitalizationScheme(result, out capitalization); } private static string GetStringFromConventionsDictionary(string namingStyleName, string optionName, IReadOnlyDictionary<string, string> conventionsDictionary) { conventionsDictionary.TryGetValue($"dotnet_naming_style.{namingStyleName}.{optionName}", out var result); return result ?? string.Empty; } private static bool TryParseCapitalizationScheme(string namingStyleCapitalization, out Capitalization capitalization) { switch (namingStyleCapitalization) { case "pascal_case": capitalization = Capitalization.PascalCase; return true; case "camel_case": capitalization = Capitalization.CamelCase; return true; case "first_word_upper": capitalization = Capitalization.FirstUpper; return true; case "all_upper": capitalization = Capitalization.AllUpper; return true; case "all_lower": capitalization = Capitalization.AllLower; return true; default: capitalization = default; return false; } } public static string ToEditorConfigString(this Capitalization capitalization) { switch (capitalization) { case Capitalization.PascalCase: return "pascal_case"; case Capitalization.CamelCase: return "camel_case"; case Capitalization.FirstUpper: return "first_word_upper"; case Capitalization.AllUpper: return "all_upper"; case Capitalization.AllLower: return "all_lower"; default: throw ExceptionUtilities.UnexpectedValue(capitalization); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/xlf/VisualBasicCompilerExtensionsResources.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../VisualBasicCompilerExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../VisualBasicCompilerExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Usuń tę wartość, gdy dodawana jest kolejna.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Operations/OperationMapBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. argument.Add(operation.Syntax, operation); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis { internal static class OperationMapBuilder { /// <summary> /// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node. /// If there is a SyntaxNode with more than one explicit IOperation, this will throw. /// </summary> internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary) { Debug.Assert(dictionary.Count == 0); Walker.Instance.Visit(root, dictionary); } private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>> { internal static readonly Walker Instance = new Walker(); public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { RecordOperation(operation, argument); return base.DefaultVisit(operation, argument); } public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument) { // In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive, // so we don't need to maintain a stack, just iterate through every level. while (true) { RecordOperation(operation, argument); Visit(operation.RightOperand, argument); if (operation.LeftOperand is IBinaryOperation nested) { operation = nested; } else { Visit(operation.LeftOperand, argument); break; } } return null; } internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { // OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation. // we need to deal with it here, however, so delegate to DefaultVisit. return DefaultVisit(operation, argument); } private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument) { if (!operation.IsImplicit) { // IOperation invariant is that all there is at most 1 non-implicit node per syntax node. argument.Add(operation.Syntax, operation); } } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Errors/MessageProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class MessageProvider Inherits CommonMessageProvider Implements IObjectWritable Public Shared ReadOnly Instance As MessageProvider = New MessageProvider() Shared Sub New() ObjectBinder.RegisterTypeReader(GetType(MessageProvider), Function(r) Instance) End Sub Private Sub New() End Sub Private ReadOnly Property IObjectWritable_ShouldReuseInSerialization As Boolean Implements IObjectWritable.ShouldReuseInSerialization Get Return True End Get End Property Private Sub WriteTo(writer As ObjectWriter) Implements IObjectWritable.WriteTo ' don't write anything since we always return the shared 'Instance' when read. End Sub Public Overrides ReadOnly Property CodePrefix As String Get ' VB uses "BC" (for Basic Compiler) to identifier its error messages. Return "BC" End Get End Property Public Overrides Function LoadMessage(code As Integer, language As CultureInfo) As String Return ErrorFactory.IdToString(DirectCast(code, ERRID), language) End Function Public Overrides Function GetMessageFormat(code As Integer) As LocalizableString Return ErrorFactory.GetMessageFormat(DirectCast(code, ERRID)) End Function Public Overrides Function GetDescription(code As Integer) As LocalizableString Return ErrorFactory.GetDescription(DirectCast(code, ERRID)) End Function Public Overrides Function GetTitle(code As Integer) As LocalizableString Return ErrorFactory.GetTitle(DirectCast(code, ERRID)) End Function Public Overrides Function GetHelpLink(code As Integer) As String Return ErrorFactory.GetHelpLink(DirectCast(code, ERRID)) End Function Public Overrides Function GetCategory(code As Integer) As String Return ErrorFactory.GetCategory(DirectCast(code, ERRID)) End Function Public Overrides Function GetSeverity(code As Integer) As DiagnosticSeverity Dim errid = DirectCast(code, ERRID) If errid = ERRID.Void Then Return InternalDiagnosticSeverity.Void ElseIf errid = ERRID.Unknown Then Return InternalDiagnosticSeverity.Unknown ElseIf ErrorFacts.IsWarning(errid) Then Return DiagnosticSeverity.Warning ElseIf ErrorFacts.IsInfo(errid) Then Return DiagnosticSeverity.Info ElseIf ErrorFacts.IsHidden(errid) Then Return DiagnosticSeverity.Hidden Else Return DiagnosticSeverity.Error End If End Function Public Overrides Function GetWarningLevel(code As Integer) As Integer Dim errorId = DirectCast(code, ERRID) If ErrorFacts.IsWarning(errorId) AndAlso code <> ERRID.WRN_BadSwitch AndAlso code <> ERRID.WRN_NoConfigInResponseFile AndAlso code <> ERRID.WRN_IgnoreModuleManifest Then Return 1 ElseIf ErrorFacts.IsInfo(errorId) OrElse ErrorFacts.IsHidden(errorId) ' Info and hidden diagnostics Return 1 Else Return 0 End If End Function Public Overrides ReadOnly Property ErrorCodeType As Type Get Return GetType(ERRID) End Get End Property Public Overrides Function CreateDiagnostic(code As Integer, location As Location, ParamArray args() As Object) As Diagnostic Return New VBDiagnostic(ErrorFactory.ErrorInfo(CType(code, ERRID), args), location) End Function Public Overrides Function CreateDiagnostic(info As DiagnosticInfo) As Diagnostic Return New VBDiagnostic(info, Location.None) End Function Public Overrides Function GetErrorDisplayString(symbol As ISymbol) As String ' show extra info for assembly if possible such as version, public key token etc. If symbol.Kind = SymbolKind.Assembly OrElse symbol.Kind = SymbolKind.Namespace Then Return symbol.ToString() End If Return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.VisualBasicShortErrorMessageFormat) End Function ' Given a message identifier (e.g., CS0219), severity, warning as error and a culture, ' get the entire prefix (e.g., "error BC42024:" for VB) used on error messages. Public Overrides Function GetMessagePrefix(id As String, severity As DiagnosticSeverity, isWarningAsError As Boolean, culture As CultureInfo) As String Return String.Format(culture, "{0} {1}", If(severity = DiagnosticSeverity.Error OrElse isWarningAsError, "error", "warning"), id) End Function Public Overrides Function GetDiagnosticReport(diagnosticInfo As DiagnosticInfo, options As CompilationOptions) As ReportDiagnostic Dim hasSourceSuppression = False Return VisualBasicDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, True, diagnosticInfo.MessageIdentifier, Location.None, diagnosticInfo.Category, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, ' We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider hasSourceSuppression) End Function Public Overrides ReadOnly Property ERR_FailedToCreateTempFile As Integer Get Return ERRID.ERR_UnableToCreateTempFile End Get End Property Public Overrides ReadOnly Property ERR_MultipleAnalyzerConfigsInSameDir As Integer Get Return ERRID.ERR_MultipleAnalyzerConfigsInSameDir End Get End Property ' command line: Public Overrides ReadOnly Property ERR_ExpectedSingleScript As Integer Get Return ERRID.ERR_ExpectedSingleScript End Get End Property Public Overrides ReadOnly Property ERR_OpenResponseFile As Integer Get Return ERRID.ERR_NoResponseFile End Get End Property Public Overrides ReadOnly Property ERR_InvalidPathMap As Integer Get Return ERRID.ERR_InvalidPathMap End Get End Property Public Overrides ReadOnly Property FTL_InvalidInputFileName As Integer Get Return ERRID.FTL_InvalidInputFileName End Get End Property Public Overrides ReadOnly Property ERR_FileNotFound As Integer Get Return ERRID.ERR_FileNotFound End Get End Property Public Overrides ReadOnly Property ERR_NoSourceFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenFileWrite As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property ERR_OutputWriteFailed As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property WRN_NoConfigNotOnCommandLine As Integer Get Return ERRID.WRN_NoConfigInResponseFile End Get End Property Public Overrides ReadOnly Property ERR_BinaryFile As Integer Get Return ERRID.ERR_BinaryFile End Get End Property Public Overrides ReadOnly Property WRN_AnalyzerCannotBeCreated As Integer Get Return ERRID.WRN_AnalyzerCannotBeCreated End Get End Property Public Overrides ReadOnly Property WRN_NoAnalyzerInAssembly As Integer Get Return ERRID.WRN_NoAnalyzerInAssembly End Get End Property Public Overrides ReadOnly Property WRN_UnableToLoadAnalyzer As Integer Get Return ERRID.WRN_UnableToLoadAnalyzer End Get End Property Public Overrides ReadOnly Property WRN_AnalyzerReferencesFramework As Integer Get Return ERRID.WRN_AnalyzerReferencesFramework End Get End Property Public Overrides ReadOnly Property INF_UnableToLoadSomeTypesInAnalyzer As Integer Get Return ERRID.INF_UnableToLoadSomeTypesInAnalyzer End Get End Property Public Overrides ReadOnly Property ERR_CantReadRulesetFile As Integer Get Return ERRID.ERR_CantReadRulesetFile End Get End Property Public Overrides ReadOnly Property ERR_CompileCancelled As Integer Get ' TODO: Add an error code for CompileCancelled Return ERRID.ERR_None End Get End Property ' parse options: Public Overrides ReadOnly Property ERR_BadSourceCodeKind As Integer Get Return ERRID.ERR_BadSourceCodeKind End Get End Property Public Overrides ReadOnly Property ERR_BadDocumentationMode As Integer Get Return ERRID.ERR_BadDocumentationMode End Get End Property ' compilation options: Public Overrides ReadOnly Property ERR_BadCompilationOptionValue As Integer Get Return ERRID.ERR_InvalidSwitchValue End Get End Property Public Overrides ReadOnly Property ERR_MutuallyExclusiveOptions As Integer Get Return ERRID.ERR_MutuallyExclusiveOptions End Get End Property ' emit options: Public Overrides ReadOnly Property ERR_InvalidDebugInformationFormat As Integer Get Return ERRID.ERR_InvalidDebugInformationFormat End Get End Property Public Overrides ReadOnly Property ERR_InvalidOutputName As Integer Get Return ERRID.ERR_InvalidOutputName End Get End Property Public Overrides ReadOnly Property ERR_InvalidFileAlignment As Integer Get Return ERRID.ERR_InvalidFileAlignment End Get End Property Public Overrides ReadOnly Property ERR_InvalidSubsystemVersion As Integer Get Return ERRID.ERR_InvalidSubsystemVersion End Get End Property Public Overrides ReadOnly Property ERR_InvalidHashAlgorithmName As Integer Get Return ERRID.ERR_InvalidHashAlgorithmName End Get End Property Public Overrides ReadOnly Property ERR_InvalidInstrumentationKind As Integer Get Return ERRID.ERR_InvalidInstrumentationKind End Get End Property ' reference manager: Public Overrides ReadOnly Property ERR_MetadataFileNotAssembly As Integer Get Return ERRID.ERR_MetaDataIsNotAssembly End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotModule As Integer Get Return ERRID.ERR_MetaDataIsNotModule End Get End Property Public Overrides ReadOnly Property ERR_InvalidAssemblyMetadata As Integer Get Return ERRID.ERR_BadMetaDataReference1 End Get End Property Public Overrides ReadOnly Property ERR_InvalidModuleMetadata As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningAssemblyFile As Integer Get Return ERRID.ERR_BadRefLib1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningModuleFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotFound As Integer Get Return ERRID.ERR_LibNotFound End Get End Property Public Overrides ReadOnly Property ERR_MetadataReferencesNotSupported As Integer Get Return ERRID.ERR_MetadataReferencesNotSupported End Get End Property Public Overrides ReadOnly Property ERR_LinkedNetmoduleMetadataMustProvideFullPEImage As Integer Get Return ERRID.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage End Get End Property Public Overrides Sub ReportDuplicateMetadataReferenceStrong(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReferenceStrong, DirectCast(location, Location), If(reference.Display, identity.GetDisplayName()), If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub Public Overrides Sub ReportDuplicateMetadataReferenceWeak(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReference2, DirectCast(location, Location), identity.Name, If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub ' signing: Public Overrides ReadOnly Property ERR_CantReadResource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyFileFailure As Integer Get Return ERRID.ERR_PublicKeyFileFailure End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyContainerFailure As Integer Get Return ERRID.ERR_PublicKeyContainerFailure End Get End Property Public Overrides ReadOnly Property ERR_OptionMustBeAbsolutePath As Integer Get Return ERRID.ERR_OptionMustBeAbsolutePath End Get End Property ' resources: Public Overrides ReadOnly Property ERR_CantOpenWin32Resource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Manifest As Integer Get Return ERRID.ERR_UnableToReadUacManifest2 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Icon As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_ErrorBuildingWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_BadWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_ResourceFileNameNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceFileName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceInModule As Integer Get Return ERRID.ERR_ResourceInModule End Get End Property ' pseudo-custom attributes Public Overrides ReadOnly Property ERR_PermissionSetAttributeFileReadError As Integer Get Return ERRID.ERR_PermissionSetAttributeFileReadError End Get End Property Protected Overrides Sub ReportInvalidAttributeArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(parameterIndex).GetLocation(), attribute.AttributeClass) End Sub Protected Overrides Sub ReportInvalidNamedArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer, attributeClass As ITypeSymbol, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation(), attributeClass) End Sub Protected Overrides Sub ReportParameterNotValidForType(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_ParameterNotValidForType, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation()) End Sub Protected Overrides Sub ReportMarshalUnmanagedTypeNotValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Protected Overrides Sub ReportMarshalUnmanagedTypeOnlyValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Protected Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired1, node.Name.GetLocation(), parameterName) End Sub Protected Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName1 As String, parameterName2 As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired2, node.Name.GetLocation(), parameterName1, parameterName2) End Sub ' PDB Writer Public Overrides ReadOnly Property ERR_EncodinglessSyntaxTree As Integer Get Return ERRID.ERR_EncodinglessSyntaxTree End Get End Property Public Overrides ReadOnly Property WRN_PdbUsingNameTooLong As Integer Get Return ERRID.WRN_PdbUsingNameTooLong End Get End Property Public Overrides ReadOnly Property WRN_PdbLocalNameTooLong As Integer Get Return ERRID.WRN_PdbLocalNameTooLong End Get End Property Public Overrides ReadOnly Property ERR_PdbWritingFailed As Integer Get Return ERRID.ERR_PDBWritingFailed End Get End Property ' PE Writer Public Overrides ReadOnly Property ERR_MetadataNameTooLong As Integer Get Return ERRID.ERR_TooLongMetadataName End Get End Property Public Overrides ReadOnly Property ERR_EncReferenceToAddedMember As Integer Get Return ERRID.ERR_EncReferenceToAddedMember End Get End Property Public Overrides ReadOnly Property ERR_TooManyUserStrings As Integer Get Return ERRID.ERR_TooManyUserStrings End Get End Property Public Overrides ReadOnly Property ERR_PeWritingFailure As Integer Get Return ERRID.ERR_PeWritingFailure End Get End Property Public Overrides ReadOnly Property ERR_ModuleEmitFailure As Integer Get Return ERRID.ERR_ModuleEmitFailure End Get End Property Public Overrides ReadOnly Property ERR_EncUpdateFailedMissingAttribute As Integer Get Return ERRID.ERR_EncUpdateFailedMissingAttribute End Get End Property Public Overrides ReadOnly Property ERR_BadAssemblyName As Integer Get Return ERRID.ERR_BadAssemblyName End Get End Property Public Overrides ReadOnly Property ERR_InvalidDebugInfo As Integer Get Return ERRID.ERR_InvalidDebugInfo End Get End Property ' Generators Public Overrides ReadOnly Property WRN_GeneratorFailedDuringInitialization As Integer Get Return ERRID.WRN_GeneratorFailedDuringInitialization End Get End Property Public Overrides ReadOnly Property WRN_GeneratorFailedDuringGeneration As Integer Get Return ERRID.WRN_GeneratorFailedDuringGeneration End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend NotInheritable Class MessageProvider Inherits CommonMessageProvider Implements IObjectWritable Public Shared ReadOnly Instance As MessageProvider = New MessageProvider() Shared Sub New() ObjectBinder.RegisterTypeReader(GetType(MessageProvider), Function(r) Instance) End Sub Private Sub New() End Sub Private ReadOnly Property IObjectWritable_ShouldReuseInSerialization As Boolean Implements IObjectWritable.ShouldReuseInSerialization Get Return True End Get End Property Private Sub WriteTo(writer As ObjectWriter) Implements IObjectWritable.WriteTo ' don't write anything since we always return the shared 'Instance' when read. End Sub Public Overrides ReadOnly Property CodePrefix As String Get ' VB uses "BC" (for Basic Compiler) to identifier its error messages. Return "BC" End Get End Property Public Overrides Function LoadMessage(code As Integer, language As CultureInfo) As String Return ErrorFactory.IdToString(DirectCast(code, ERRID), language) End Function Public Overrides Function GetMessageFormat(code As Integer) As LocalizableString Return ErrorFactory.GetMessageFormat(DirectCast(code, ERRID)) End Function Public Overrides Function GetDescription(code As Integer) As LocalizableString Return ErrorFactory.GetDescription(DirectCast(code, ERRID)) End Function Public Overrides Function GetTitle(code As Integer) As LocalizableString Return ErrorFactory.GetTitle(DirectCast(code, ERRID)) End Function Public Overrides Function GetHelpLink(code As Integer) As String Return ErrorFactory.GetHelpLink(DirectCast(code, ERRID)) End Function Public Overrides Function GetCategory(code As Integer) As String Return ErrorFactory.GetCategory(DirectCast(code, ERRID)) End Function Public Overrides Function GetSeverity(code As Integer) As DiagnosticSeverity Dim errid = DirectCast(code, ERRID) If errid = ERRID.Void Then Return InternalDiagnosticSeverity.Void ElseIf errid = ERRID.Unknown Then Return InternalDiagnosticSeverity.Unknown ElseIf ErrorFacts.IsWarning(errid) Then Return DiagnosticSeverity.Warning ElseIf ErrorFacts.IsInfo(errid) Then Return DiagnosticSeverity.Info ElseIf ErrorFacts.IsHidden(errid) Then Return DiagnosticSeverity.Hidden Else Return DiagnosticSeverity.Error End If End Function Public Overrides Function GetWarningLevel(code As Integer) As Integer Dim errorId = DirectCast(code, ERRID) If ErrorFacts.IsWarning(errorId) AndAlso code <> ERRID.WRN_BadSwitch AndAlso code <> ERRID.WRN_NoConfigInResponseFile AndAlso code <> ERRID.WRN_IgnoreModuleManifest Then Return 1 ElseIf ErrorFacts.IsInfo(errorId) OrElse ErrorFacts.IsHidden(errorId) ' Info and hidden diagnostics Return 1 Else Return 0 End If End Function Public Overrides ReadOnly Property ErrorCodeType As Type Get Return GetType(ERRID) End Get End Property Public Overrides Function CreateDiagnostic(code As Integer, location As Location, ParamArray args() As Object) As Diagnostic Return New VBDiagnostic(ErrorFactory.ErrorInfo(CType(code, ERRID), args), location) End Function Public Overrides Function CreateDiagnostic(info As DiagnosticInfo) As Diagnostic Return New VBDiagnostic(info, Location.None) End Function Public Overrides Function GetErrorDisplayString(symbol As ISymbol) As String ' show extra info for assembly if possible such as version, public key token etc. If symbol.Kind = SymbolKind.Assembly OrElse symbol.Kind = SymbolKind.Namespace Then Return symbol.ToString() End If Return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.VisualBasicShortErrorMessageFormat) End Function ' Given a message identifier (e.g., CS0219), severity, warning as error and a culture, ' get the entire prefix (e.g., "error BC42024:" for VB) used on error messages. Public Overrides Function GetMessagePrefix(id As String, severity As DiagnosticSeverity, isWarningAsError As Boolean, culture As CultureInfo) As String Return String.Format(culture, "{0} {1}", If(severity = DiagnosticSeverity.Error OrElse isWarningAsError, "error", "warning"), id) End Function Public Overrides Function GetDiagnosticReport(diagnosticInfo As DiagnosticInfo, options As CompilationOptions) As ReportDiagnostic Dim hasSourceSuppression = False Return VisualBasicDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, True, diagnosticInfo.MessageIdentifier, Location.None, diagnosticInfo.Category, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, ' We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider hasSourceSuppression) End Function Public Overrides ReadOnly Property ERR_FailedToCreateTempFile As Integer Get Return ERRID.ERR_UnableToCreateTempFile End Get End Property Public Overrides ReadOnly Property ERR_MultipleAnalyzerConfigsInSameDir As Integer Get Return ERRID.ERR_MultipleAnalyzerConfigsInSameDir End Get End Property ' command line: Public Overrides ReadOnly Property ERR_ExpectedSingleScript As Integer Get Return ERRID.ERR_ExpectedSingleScript End Get End Property Public Overrides ReadOnly Property ERR_OpenResponseFile As Integer Get Return ERRID.ERR_NoResponseFile End Get End Property Public Overrides ReadOnly Property ERR_InvalidPathMap As Integer Get Return ERRID.ERR_InvalidPathMap End Get End Property Public Overrides ReadOnly Property FTL_InvalidInputFileName As Integer Get Return ERRID.FTL_InvalidInputFileName End Get End Property Public Overrides ReadOnly Property ERR_FileNotFound As Integer Get Return ERRID.ERR_FileNotFound End Get End Property Public Overrides ReadOnly Property ERR_NoSourceFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenFileWrite As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property ERR_OutputWriteFailed As Integer Get Return ERRID.ERR_CantOpenFileWrite End Get End Property Public Overrides ReadOnly Property WRN_NoConfigNotOnCommandLine As Integer Get Return ERRID.WRN_NoConfigInResponseFile End Get End Property Public Overrides ReadOnly Property ERR_BinaryFile As Integer Get Return ERRID.ERR_BinaryFile End Get End Property Public Overrides ReadOnly Property WRN_AnalyzerCannotBeCreated As Integer Get Return ERRID.WRN_AnalyzerCannotBeCreated End Get End Property Public Overrides ReadOnly Property WRN_NoAnalyzerInAssembly As Integer Get Return ERRID.WRN_NoAnalyzerInAssembly End Get End Property Public Overrides ReadOnly Property WRN_UnableToLoadAnalyzer As Integer Get Return ERRID.WRN_UnableToLoadAnalyzer End Get End Property Public Overrides ReadOnly Property WRN_AnalyzerReferencesFramework As Integer Get Return ERRID.WRN_AnalyzerReferencesFramework End Get End Property Public Overrides ReadOnly Property INF_UnableToLoadSomeTypesInAnalyzer As Integer Get Return ERRID.INF_UnableToLoadSomeTypesInAnalyzer End Get End Property Public Overrides ReadOnly Property ERR_CantReadRulesetFile As Integer Get Return ERRID.ERR_CantReadRulesetFile End Get End Property Public Overrides ReadOnly Property ERR_CompileCancelled As Integer Get ' TODO: Add an error code for CompileCancelled Return ERRID.ERR_None End Get End Property ' parse options: Public Overrides ReadOnly Property ERR_BadSourceCodeKind As Integer Get Return ERRID.ERR_BadSourceCodeKind End Get End Property Public Overrides ReadOnly Property ERR_BadDocumentationMode As Integer Get Return ERRID.ERR_BadDocumentationMode End Get End Property ' compilation options: Public Overrides ReadOnly Property ERR_BadCompilationOptionValue As Integer Get Return ERRID.ERR_InvalidSwitchValue End Get End Property Public Overrides ReadOnly Property ERR_MutuallyExclusiveOptions As Integer Get Return ERRID.ERR_MutuallyExclusiveOptions End Get End Property ' emit options: Public Overrides ReadOnly Property ERR_InvalidDebugInformationFormat As Integer Get Return ERRID.ERR_InvalidDebugInformationFormat End Get End Property Public Overrides ReadOnly Property ERR_InvalidOutputName As Integer Get Return ERRID.ERR_InvalidOutputName End Get End Property Public Overrides ReadOnly Property ERR_InvalidFileAlignment As Integer Get Return ERRID.ERR_InvalidFileAlignment End Get End Property Public Overrides ReadOnly Property ERR_InvalidSubsystemVersion As Integer Get Return ERRID.ERR_InvalidSubsystemVersion End Get End Property Public Overrides ReadOnly Property ERR_InvalidHashAlgorithmName As Integer Get Return ERRID.ERR_InvalidHashAlgorithmName End Get End Property Public Overrides ReadOnly Property ERR_InvalidInstrumentationKind As Integer Get Return ERRID.ERR_InvalidInstrumentationKind End Get End Property ' reference manager: Public Overrides ReadOnly Property ERR_MetadataFileNotAssembly As Integer Get Return ERRID.ERR_MetaDataIsNotAssembly End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotModule As Integer Get Return ERRID.ERR_MetaDataIsNotModule End Get End Property Public Overrides ReadOnly Property ERR_InvalidAssemblyMetadata As Integer Get Return ERRID.ERR_BadMetaDataReference1 End Get End Property Public Overrides ReadOnly Property ERR_InvalidModuleMetadata As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningAssemblyFile As Integer Get Return ERRID.ERR_BadRefLib1 End Get End Property Public Overrides ReadOnly Property ERR_ErrorOpeningModuleFile As Integer Get Return ERRID.ERR_BadModuleFile1 End Get End Property Public Overrides ReadOnly Property ERR_MetadataFileNotFound As Integer Get Return ERRID.ERR_LibNotFound End Get End Property Public Overrides ReadOnly Property ERR_MetadataReferencesNotSupported As Integer Get Return ERRID.ERR_MetadataReferencesNotSupported End Get End Property Public Overrides ReadOnly Property ERR_LinkedNetmoduleMetadataMustProvideFullPEImage As Integer Get Return ERRID.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage End Get End Property Public Overrides Sub ReportDuplicateMetadataReferenceStrong(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReferenceStrong, DirectCast(location, Location), If(reference.Display, identity.GetDisplayName()), If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub Public Overrides Sub ReportDuplicateMetadataReferenceWeak(diagnostics As DiagnosticBag, location As Location, reference As MetadataReference, identity As AssemblyIdentity, equivalentReference As MetadataReference, equivalentIdentity As AssemblyIdentity) diagnostics.Add(ERRID.ERR_DuplicateReference2, DirectCast(location, Location), identity.Name, If(equivalentReference.Display, equivalentIdentity.GetDisplayName())) End Sub ' signing: Public Overrides ReadOnly Property ERR_CantReadResource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyFileFailure As Integer Get Return ERRID.ERR_PublicKeyFileFailure End Get End Property Public Overrides ReadOnly Property ERR_PublicKeyContainerFailure As Integer Get Return ERRID.ERR_PublicKeyContainerFailure End Get End Property Public Overrides ReadOnly Property ERR_OptionMustBeAbsolutePath As Integer Get Return ERRID.ERR_OptionMustBeAbsolutePath End Get End Property ' resources: Public Overrides ReadOnly Property ERR_CantOpenWin32Resource As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Manifest As Integer Get Return ERRID.ERR_UnableToReadUacManifest2 End Get End Property Public Overrides ReadOnly Property ERR_CantOpenWin32Icon As Integer Get Return ERRID.ERR_UnableToOpenResourceFile1 'TODO: refine (DevDiv #12914) End Get End Property Public Overrides ReadOnly Property ERR_ErrorBuildingWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_BadWin32Resource As Integer Get Return ERRID.ERR_ErrorCreatingWin32ResourceFile End Get End Property Public Overrides ReadOnly Property ERR_ResourceFileNameNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceFileName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceNotUnique As Integer Get Return ERRID.ERR_DuplicateResourceName1 End Get End Property Public Overrides ReadOnly Property ERR_ResourceInModule As Integer Get Return ERRID.ERR_ResourceInModule End Get End Property ' pseudo-custom attributes Public Overrides ReadOnly Property ERR_PermissionSetAttributeFileReadError As Integer Get Return ERRID.ERR_PermissionSetAttributeFileReadError End Get End Property Protected Overrides Sub ReportInvalidAttributeArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(parameterIndex).GetLocation(), attribute.AttributeClass) End Sub Protected Overrides Sub ReportInvalidNamedArgument(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer, attributeClass As ITypeSymbol, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_BadAttribute1, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation(), attributeClass) End Sub Protected Overrides Sub ReportParameterNotValidForType(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, namedArgumentIndex As Integer) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_ParameterNotValidForType, node.ArgumentList.Arguments(namedArgumentIndex).GetLocation()) End Sub Protected Overrides Sub ReportMarshalUnmanagedTypeNotValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeNotValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Protected Overrides Sub ReportMarshalUnmanagedTypeOnlyValidForFields(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterIndex As Integer, unmanagedTypeName As String, attribute As AttributeData) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_MarshalUnmanagedTypeOnlyValidForFields, node.ArgumentList.Arguments(parameterIndex).GetLocation(), unmanagedTypeName) End Sub Protected Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired1, node.Name.GetLocation(), parameterName) End Sub Protected Overrides Sub ReportAttributeParameterRequired(diagnostics As DiagnosticBag, attributeSyntax As SyntaxNode, parameterName1 As String, parameterName2 As String) Dim node = DirectCast(attributeSyntax, AttributeSyntax) diagnostics.Add(ERRID.ERR_AttributeParameterRequired2, node.Name.GetLocation(), parameterName1, parameterName2) End Sub ' PDB Writer Public Overrides ReadOnly Property ERR_EncodinglessSyntaxTree As Integer Get Return ERRID.ERR_EncodinglessSyntaxTree End Get End Property Public Overrides ReadOnly Property WRN_PdbUsingNameTooLong As Integer Get Return ERRID.WRN_PdbUsingNameTooLong End Get End Property Public Overrides ReadOnly Property WRN_PdbLocalNameTooLong As Integer Get Return ERRID.WRN_PdbLocalNameTooLong End Get End Property Public Overrides ReadOnly Property ERR_PdbWritingFailed As Integer Get Return ERRID.ERR_PDBWritingFailed End Get End Property ' PE Writer Public Overrides ReadOnly Property ERR_MetadataNameTooLong As Integer Get Return ERRID.ERR_TooLongMetadataName End Get End Property Public Overrides ReadOnly Property ERR_EncReferenceToAddedMember As Integer Get Return ERRID.ERR_EncReferenceToAddedMember End Get End Property Public Overrides ReadOnly Property ERR_TooManyUserStrings As Integer Get Return ERRID.ERR_TooManyUserStrings End Get End Property Public Overrides ReadOnly Property ERR_PeWritingFailure As Integer Get Return ERRID.ERR_PeWritingFailure End Get End Property Public Overrides ReadOnly Property ERR_ModuleEmitFailure As Integer Get Return ERRID.ERR_ModuleEmitFailure End Get End Property Public Overrides ReadOnly Property ERR_EncUpdateFailedMissingAttribute As Integer Get Return ERRID.ERR_EncUpdateFailedMissingAttribute End Get End Property Public Overrides ReadOnly Property ERR_BadAssemblyName As Integer Get Return ERRID.ERR_BadAssemblyName End Get End Property Public Overrides ReadOnly Property ERR_InvalidDebugInfo As Integer Get Return ERRID.ERR_InvalidDebugInfo End Get End Property ' Generators Public Overrides ReadOnly Property WRN_GeneratorFailedDuringInitialization As Integer Get Return ERRID.WRN_GeneratorFailedDuringInitialization End Get End Property Public Overrides ReadOnly Property WRN_GeneratorFailedDuringGeneration As Integer Get Return ERRID.WRN_GeneratorFailedDuringGeneration End Get End Property End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/LanguageServices/VisualBasicSymbolDisplayService.SymbolDescriptionBuilder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices Partial Friend Class VisualBasicSymbolDisplayService Protected Class SymbolDescriptionBuilder Inherits AbstractSymbolDescriptionBuilder Private Shared ReadOnly s_minimallyQualifiedFormat As SymbolDisplayFormat = SymbolDisplayFormat.MinimallyQualifiedFormat _ .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) _ .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) Private Shared ReadOnly s_minimallyQualifiedFormatWithConstants As SymbolDisplayFormat = s_minimallyQualifiedFormat _ .AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue) _ .AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue) _ .AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) Private Shared ReadOnly s_minimallyQualifiedFormatWithConstantsAndModifiers As SymbolDisplayFormat = s_minimallyQualifiedFormatWithConstants _ .AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers) Public Sub New(semanticModel As SemanticModel, position As Integer, workspace As Workspace, anonymousTypeDisplayService As IAnonymousTypeDisplayService, cancellationToken As CancellationToken) MyBase.New(semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken) End Sub Protected Overrides Sub AddDeprecatedPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(VBFeaturesResources.Deprecated), Punctuation(")"), Space()) End Sub Protected Overrides Sub AddExtensionPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Extension), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddAwaitablePrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Awaitable), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddAwaitableExtensionPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Awaitable_Extension), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddEnumUnderlyingTypeSeparator() AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Keyword("As"), Space()) End Sub Protected Overrides Function GetInitializerSourcePartsAsync(symbol As ISymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) If TypeOf symbol Is IParameterSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, IParameterSymbol)) ElseIf TypeOf symbol Is ILocalSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, ILocalSymbol)) ElseIf TypeOf symbol Is IFieldSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, IFieldSymbol)) End If Return SpecializedTasks.EmptyImmutableArray(Of SymbolDisplayPart) End Function Protected Overrides Function ToMinimalDisplayParts(symbol As ISymbol, semanticModel As SemanticModel, position As Integer, format As SymbolDisplayFormat) As ImmutableArray(Of SymbolDisplayPart) Return CodeAnalysis.VisualBasic.ToMinimalDisplayParts(symbol, semanticModel, position, format) End Function Protected Overrides Function GetNavigationHint(symbol As ISymbol) As String Return If(symbol Is Nothing, Nothing, CodeAnalysis.VisualBasic.SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat)) End Function Private Async Function GetFirstDeclarationAsync(Of T As SyntaxNode)(symbol As ISymbol) As Task(Of T) For Each syntaxRef In symbol.DeclaringSyntaxReferences Dim syntax = Await syntaxRef.GetSyntaxAsync(Me.CancellationToken).ConfigureAwait(False) Dim casted = TryCast(syntax, T) If casted IsNot Nothing Then Return casted End If Next Return Nothing End Function Private Async Function GetDeclarationsAsync(Of T As SyntaxNode)(symbol As ISymbol) As Task(Of List(Of T)) Dim list = New List(Of T)() For Each syntaxRef In symbol.DeclaringSyntaxReferences Dim syntax = Await syntaxRef.GetSyntaxAsync(Me.CancellationToken).ConfigureAwait(False) Dim casted = TryCast(syntax, T) If casted IsNot Nothing Then list.Add(casted) End If Next Return list End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As IParameterSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim syntax = Await GetFirstDeclarationAsync(Of ParameterSyntax)(symbol).ConfigureAwait(False) If syntax IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(False) End If Return ImmutableArray(Of SymbolDisplayPart).Empty End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As ILocalSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim ids = Await GetDeclarationsAsync(Of ModifiedIdentifierSyntax)(symbol).ConfigureAwait(False) Dim syntax = ids.Select(Function(i) i.Parent).OfType(Of VariableDeclaratorSyntax).FirstOrDefault() If syntax IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(False) End If Return Nothing End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As IFieldSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim ids = Await GetDeclarationsAsync(Of ModifiedIdentifierSyntax)(symbol).ConfigureAwait(False) Dim variableDeclarator = ids.Select(Function(i) i.Parent).OfType(Of VariableDeclaratorSyntax).FirstOrDefault() If variableDeclarator IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(variableDeclarator.Initializer).ConfigureAwait(False) End If Dim enumMemberDeclaration = Await GetFirstDeclarationAsync(Of EnumMemberDeclarationSyntax)(symbol).ConfigureAwait(False) If enumMemberDeclaration IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(enumMemberDeclaration.Initializer).ConfigureAwait(False) End If Return Nothing End Function Private Overloads Async Function GetInitializerSourcePartsAsync(equalsValue As EqualsValueSyntax) As Task(Of ImmutableArray(Of SymbolDisplayPart)) If equalsValue IsNot Nothing AndAlso equalsValue.Value IsNot Nothing Then Dim semanticModel = GetSemanticModel(equalsValue.SyntaxTree) If semanticModel IsNot Nothing Then Return Await Classifier.GetClassifiedSymbolDisplayPartsAsync( semanticModel, equalsValue.Value.Span, Me.Workspace, cancellationToken:=Me.CancellationToken).ConfigureAwait(False) End If End If Return Nothing End Function Protected Overrides Sub AddCaptures(symbol As ISymbol) Dim method = TryCast(symbol, IMethodSymbol) If method IsNot Nothing AndAlso method.ContainingSymbol.IsKind(SymbolKind.Method) Then Dim syntax = method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() AddCaptures(syntax) End If End Sub Protected Overrides ReadOnly Property MinimallyQualifiedFormat As SymbolDisplayFormat Get Return s_minimallyQualifiedFormat End Get End Property Protected Overrides ReadOnly Property MinimallyQualifiedFormatWithConstants As SymbolDisplayFormat Get Return s_minimallyQualifiedFormatWithConstants End Get End Property Protected Overrides ReadOnly Property MinimallyQualifiedFormatWithConstantsAndModifiers As SymbolDisplayFormat Get Return s_minimallyQualifiedFormatWithConstantsAndModifiers End Get End Property End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LanguageServices Partial Friend Class VisualBasicSymbolDisplayService Protected Class SymbolDescriptionBuilder Inherits AbstractSymbolDescriptionBuilder Private Shared ReadOnly s_minimallyQualifiedFormat As SymbolDisplayFormat = SymbolDisplayFormat.MinimallyQualifiedFormat _ .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName) _ .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) Private Shared ReadOnly s_minimallyQualifiedFormatWithConstants As SymbolDisplayFormat = s_minimallyQualifiedFormat _ .AddLocalOptions(SymbolDisplayLocalOptions.IncludeConstantValue) _ .AddMemberOptions(SymbolDisplayMemberOptions.IncludeConstantValue) _ .AddParameterOptions(SymbolDisplayParameterOptions.IncludeDefaultValue) Private Shared ReadOnly s_minimallyQualifiedFormatWithConstantsAndModifiers As SymbolDisplayFormat = s_minimallyQualifiedFormatWithConstants _ .AddMemberOptions(SymbolDisplayMemberOptions.IncludeModifiers) Public Sub New(semanticModel As SemanticModel, position As Integer, workspace As Workspace, anonymousTypeDisplayService As IAnonymousTypeDisplayService, cancellationToken As CancellationToken) MyBase.New(semanticModel, position, workspace, anonymousTypeDisplayService, cancellationToken) End Sub Protected Overrides Sub AddDeprecatedPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("("), PlainText(VBFeaturesResources.Deprecated), Punctuation(")"), Space()) End Sub Protected Overrides Sub AddExtensionPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Extension), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddAwaitablePrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Awaitable), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddAwaitableExtensionPrefix() AddToGroup(SymbolDescriptionGroups.MainDescription, Punctuation("<"), PlainText(VBFeaturesResources.Awaitable_Extension), Punctuation(">"), Space()) End Sub Protected Overrides Sub AddEnumUnderlyingTypeSeparator() AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Keyword("As"), Space()) End Sub Protected Overrides Function GetInitializerSourcePartsAsync(symbol As ISymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) If TypeOf symbol Is IParameterSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, IParameterSymbol)) ElseIf TypeOf symbol Is ILocalSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, ILocalSymbol)) ElseIf TypeOf symbol Is IFieldSymbol Then Return GetInitializerSourcePartsAsync(DirectCast(symbol, IFieldSymbol)) End If Return SpecializedTasks.EmptyImmutableArray(Of SymbolDisplayPart) End Function Protected Overrides Function ToMinimalDisplayParts(symbol As ISymbol, semanticModel As SemanticModel, position As Integer, format As SymbolDisplayFormat) As ImmutableArray(Of SymbolDisplayPart) Return CodeAnalysis.VisualBasic.ToMinimalDisplayParts(symbol, semanticModel, position, format) End Function Protected Overrides Function GetNavigationHint(symbol As ISymbol) As String Return If(symbol Is Nothing, Nothing, CodeAnalysis.VisualBasic.SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.MinimallyQualifiedFormat)) End Function Private Async Function GetFirstDeclarationAsync(Of T As SyntaxNode)(symbol As ISymbol) As Task(Of T) For Each syntaxRef In symbol.DeclaringSyntaxReferences Dim syntax = Await syntaxRef.GetSyntaxAsync(Me.CancellationToken).ConfigureAwait(False) Dim casted = TryCast(syntax, T) If casted IsNot Nothing Then Return casted End If Next Return Nothing End Function Private Async Function GetDeclarationsAsync(Of T As SyntaxNode)(symbol As ISymbol) As Task(Of List(Of T)) Dim list = New List(Of T)() For Each syntaxRef In symbol.DeclaringSyntaxReferences Dim syntax = Await syntaxRef.GetSyntaxAsync(Me.CancellationToken).ConfigureAwait(False) Dim casted = TryCast(syntax, T) If casted IsNot Nothing Then list.Add(casted) End If Next Return list End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As IParameterSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim syntax = Await GetFirstDeclarationAsync(Of ParameterSyntax)(symbol).ConfigureAwait(False) If syntax IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(syntax.Default).ConfigureAwait(False) End If Return ImmutableArray(Of SymbolDisplayPart).Empty End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As ILocalSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim ids = Await GetDeclarationsAsync(Of ModifiedIdentifierSyntax)(symbol).ConfigureAwait(False) Dim syntax = ids.Select(Function(i) i.Parent).OfType(Of VariableDeclaratorSyntax).FirstOrDefault() If syntax IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(syntax.Initializer).ConfigureAwait(False) End If Return Nothing End Function Private Overloads Async Function GetInitializerSourcePartsAsync(symbol As IFieldSymbol) As Task(Of ImmutableArray(Of SymbolDisplayPart)) Dim ids = Await GetDeclarationsAsync(Of ModifiedIdentifierSyntax)(symbol).ConfigureAwait(False) Dim variableDeclarator = ids.Select(Function(i) i.Parent).OfType(Of VariableDeclaratorSyntax).FirstOrDefault() If variableDeclarator IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(variableDeclarator.Initializer).ConfigureAwait(False) End If Dim enumMemberDeclaration = Await GetFirstDeclarationAsync(Of EnumMemberDeclarationSyntax)(symbol).ConfigureAwait(False) If enumMemberDeclaration IsNot Nothing Then Return Await GetInitializerSourcePartsAsync(enumMemberDeclaration.Initializer).ConfigureAwait(False) End If Return Nothing End Function Private Overloads Async Function GetInitializerSourcePartsAsync(equalsValue As EqualsValueSyntax) As Task(Of ImmutableArray(Of SymbolDisplayPart)) If equalsValue IsNot Nothing AndAlso equalsValue.Value IsNot Nothing Then Dim semanticModel = GetSemanticModel(equalsValue.SyntaxTree) If semanticModel IsNot Nothing Then Return Await Classifier.GetClassifiedSymbolDisplayPartsAsync( semanticModel, equalsValue.Value.Span, Me.Workspace, cancellationToken:=Me.CancellationToken).ConfigureAwait(False) End If End If Return Nothing End Function Protected Overrides Sub AddCaptures(symbol As ISymbol) Dim method = TryCast(symbol, IMethodSymbol) If method IsNot Nothing AndAlso method.ContainingSymbol.IsKind(SymbolKind.Method) Then Dim syntax = method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() AddCaptures(syntax) End If End Sub Protected Overrides ReadOnly Property MinimallyQualifiedFormat As SymbolDisplayFormat Get Return s_minimallyQualifiedFormat End Get End Property Protected Overrides ReadOnly Property MinimallyQualifiedFormatWithConstants As SymbolDisplayFormat Get Return s_minimallyQualifiedFormatWithConstants End Get End Property Protected Overrides ReadOnly Property MinimallyQualifiedFormatWithConstantsAndModifiers As SymbolDisplayFormat Get Return s_minimallyQualifiedFormatWithConstantsAndModifiers End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/CodeRefactorings/UseExplicitOrImplicitType/UseImplicitTypeCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseImplicitType), Shared] internal partial class UseImplicitTypeCodeRefactoringProvider : AbstractUseTypeCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeRefactoringProvider() { } protected override string Title => CSharpAnalyzersResources.Use_implicit_type; protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.FindAnalyzableType(node, semanticModel, cancellationToken); protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, optionSet, cancellationToken); protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); return Task.CompletedTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.TypeStyle; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.UseImplicitType { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.UseImplicitType), Shared] internal partial class UseImplicitTypeCodeRefactoringProvider : AbstractUseTypeCodeRefactoringProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseImplicitTypeCodeRefactoringProvider() { } protected override string Title => CSharpAnalyzersResources.Use_implicit_type; protected override TypeSyntax FindAnalyzableType(SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.FindAnalyzableType(node, semanticModel, cancellationToken); protected override TypeStyleResult AnalyzeTypeName(TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) => CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName(typeName, semanticModel, optionSet, cancellationToken); protected override Task HandleDeclarationAsync(Document document, SyntaxEditor editor, TypeSyntax type, CancellationToken cancellationToken) { UseImplicitTypeCodeFixProvider.ReplaceTypeWithVar(editor, type); return Task.CompletedTask; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Interactive/vbi/vbi.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <StartupObject>Sub Main</StartupObject> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <RootNamespace></RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> <None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </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"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <StartupObject>Sub Main</StartupObject> <TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks> <RootNamespace></RootNamespace> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Scripting.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> <None Include="vbi.coreclr.rsp" Condition="'$(TargetFramework)' == 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Include="vbi.desktop.rsp" Condition="'$(TargetFramework)' != 'netcoreapp3.1'"> <Link>vbi.rsp</Link> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> </Project>
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/TypeParameterSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class TypeParameterSymbolExtensions { public static bool DependsOn(this TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2) { Debug.Assert((object)typeParameter1 != null); Debug.Assert((object)typeParameter2 != null); Stack<TypeParameterSymbol>? stack = null; HashSet<TypeParameterSymbol>? visited = null; while (true) { foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol typeParameter) { if (typeParameter.Equals(typeParameter2)) { return true; } visited ??= new HashSet<TypeParameterSymbol>(); if (visited.Add(typeParameter)) { stack ??= new Stack<TypeParameterSymbol>(); stack.Push(typeParameter); } } } if (stack is null || stack.Count == 0) { break; } typeParameter1 = stack.Pop(); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class TypeParameterSymbolExtensions { public static bool DependsOn(this TypeParameterSymbol typeParameter1, TypeParameterSymbol typeParameter2) { Debug.Assert((object)typeParameter1 != null); Debug.Assert((object)typeParameter2 != null); Stack<TypeParameterSymbol>? stack = null; HashSet<TypeParameterSymbol>? visited = null; while (true) { foreach (var constraintType in typeParameter1.ConstraintTypesNoUseSiteDiagnostics) { if (constraintType.Type is TypeParameterSymbol typeParameter) { if (typeParameter.Equals(typeParameter2)) { return true; } visited ??= new HashSet<TypeParameterSymbol>(); if (visited.Add(typeParameter)) { stack ??= new Stack<TypeParameterSymbol>(); stack.Push(typeParameter); } } } if (stack is null || stack.Count == 0) { break; } typeParameter1 = stack.Pop(); } return false; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Tagging/AbstractAsynchronousTaggerProvider.TagSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <para>The <see cref="TagSource"/> is the core part of our asynchronous /// tagging infrastructure. It is the coordinator between <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>s, /// <see cref="ITaggerEventSource"/>s, and <see cref="ITagger{T}"/>s.</para> /// /// <para>The <see cref="TagSource"/> is the type that actually owns the /// list of cached tags. When an <see cref="ITaggerEventSource"/> says tags need to be recomputed, /// the tag source starts the computation and calls <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> to build /// the new list of tags. When that's done, the tags are stored in <see cref="CachedTagTrees"/>. The /// tagger, when asked for tags from the editor, then returns the tags that are stored in /// <see cref="CachedTagTrees"/></para> /// /// <para>There is a one-to-many relationship between <see cref="TagSource"/>s /// and <see cref="ITagger{T}"/>s. Special cases, like reference highlighting (which processes multiple /// subject buffers at once) have their own providers and tag source derivations.</para> /// </summary> private sealed partial class TagSource : ForegroundThreadAffinitizedObject { /// <summary> /// If we get more than this many differences, then we just issue it as a single change /// notification. The number has been completely made up without any data to support it. /// /// Internal for testing purposes. /// </summary> private const int CoalesceDifferenceCount = 10; #region Fields that can be accessed from either thread private readonly AbstractAsynchronousTaggerProvider<TTag> _dataSource; /// <summary> /// async operation notifier /// </summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// Work queue that collects high priority requests to call TagsChanged with. /// </summary> private readonly AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection> _highPriTagsChangedQueue; /// <summary> /// Work queue that collects normal priority requests to call TagsChanged with. /// </summary> private readonly AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection> _normalPriTagsChangedQueue; private readonly ReferenceCountedDisposable<TagSourceState> _tagSourceState = new(new TagSourceState()); #endregion #region Fields that can only be accessed from the foreground thread private readonly ITextView _textViewOpt; private readonly ITextBuffer _subjectBuffer; /// <summary> /// Our tagger event source that lets us know when we should call into the tag producer for /// new tags. /// </summary> private readonly ITaggerEventSource _eventSource; /// <summary> /// accumulated text changes since last tag calculation /// </summary> private TextChangeRange? _accumulatedTextChanges_doNotAccessDirectly; private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _cachedTagTrees_doNotAccessDirectly = ImmutableDictionary.Create<ITextBuffer, TagSpanIntervalTree<TTag>>(); private object? _state_doNotAccessDirecty; /// <summary> /// Keep track of if we are processing the first <see cref="ITagger{T}.GetTags"/> request. If our provider returns /// <see langword="true"/> for <see cref="AbstractAsynchronousTaggerProvider{TTag}.ComputeInitialTagsSynchronously"/>, /// then we'll want to synchronously block then and only then for tags. /// </summary> private bool _firstTagsRequest = true; #endregion public TagSource( ITextView textViewOpt, ITextBuffer subjectBuffer, AbstractAsynchronousTaggerProvider<TTag> dataSource, IAsynchronousOperationListener asyncListener) : base(dataSource.ThreadingContext) { this.AssertIsForeground(); if (dataSource.SpanTrackingMode == SpanTrackingMode.Custom) throw new ArgumentException("SpanTrackingMode.Custom not allowed.", "spanTrackingMode"); _subjectBuffer = subjectBuffer; _textViewOpt = textViewOpt; _dataSource = dataSource; _asyncListener = asyncListener; _highPriTagsChangedQueue = new AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection>( TaggerDelay.NearImmediate.ComputeTimeDelay(), ProcessTagsChangedAsync, equalityComparer: null, asyncListener, _tagSourceState.Target.DisposalToken); if (_dataSource.AddedTagNotificationDelay == TaggerDelay.NearImmediate) { // if the tagger wants "added tags" to be reported "NearImmediate"ly, then just reuse // the "high pri" queue as that already reports things at that cadence. _normalPriTagsChangedQueue = _highPriTagsChangedQueue; } else { _normalPriTagsChangedQueue = new AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection>( _dataSource.AddedTagNotificationDelay.ComputeTimeDelay(), ProcessTagsChangedAsync, equalityComparer: null, asyncListener, _tagSourceState.Target.DisposalToken); } DebugRecordInitialStackTrace(); _eventSource = CreateEventSource(); Connect(); // Start computing the initial set of tags immediately. We want to get the UI // to a complete state as soon as possible. EnqueueWork(initialTags: true); return; void Connect() { this.AssertIsForeground(); _eventSource.Changed += OnEventSourceChanged; if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges)) { _subjectBuffer.Changed += OnSubjectBufferChanged; } if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag)) { if (_textViewOpt == null) { throw new ArgumentException( nameof(_dataSource.CaretChangeBehavior) + " can only be specified for an " + nameof(IViewTaggerProvider)); } _textViewOpt.Caret.PositionChanged += OnCaretPositionChanged; } // Tell the interaction object to start issuing events. _eventSource.Connect(); } } private void Dispose() { _tagSourceState.Dispose(); _dataSource.RemoveTagSource(_textViewOpt, _subjectBuffer); GC.SuppressFinalize(this); Disconnect(); return; void Disconnect() { this.AssertIsForeground(); // Tell the interaction object to stop issuing events. _eventSource.Disconnect(); if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag)) { _textViewOpt.Caret.PositionChanged -= OnCaretPositionChanged; } if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges)) { _subjectBuffer.Changed -= OnSubjectBufferChanged; } _eventSource.Changed -= OnEventSourceChanged; } } private ITaggerEventSource CreateEventSource() { var eventSource = _dataSource.CreateEventSource(_textViewOpt, _subjectBuffer); // If there are any options specified for this tagger, then also hook up event // notifications for when those options change. var optionChangedEventSources = _dataSource.Options.Concat<IOption>(_dataSource.PerLanguageOptions) .Select(o => TaggerEventSources.OnOptionChanged(_subjectBuffer, o)).ToList(); if (optionChangedEventSources.Count == 0) { // No options specified for this tagger. So just keep the event source as is. return eventSource; } optionChangedEventSources.Add(eventSource); return TaggerEventSources.Compose(optionChangedEventSources); } private TextChangeRange? AccumulatedTextChanges { get { this.AssertIsForeground(); return _accumulatedTextChanges_doNotAccessDirectly; } set { this.AssertIsForeground(); _accumulatedTextChanges_doNotAccessDirectly = value; } } private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> CachedTagTrees { get { this.AssertIsForeground(); return _cachedTagTrees_doNotAccessDirectly; } set { this.AssertIsForeground(); _cachedTagTrees_doNotAccessDirectly = value; } } private object? State { get { this.AssertIsForeground(); return _state_doNotAccessDirecty; } set { this.AssertIsForeground(); _state_doNotAccessDirecty = value; } } private void RaiseTagsChanged(ITextBuffer buffer, DiffResult difference) { this.AssertIsForeground(); if (difference.Count == 0) { // nothing changed. return; } OnTagsChangedForBuffer(SpecializedCollections.SingletonCollection( new KeyValuePair<ITextBuffer, DiffResult>(buffer, difference)), initialTags: false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { internal partial class AbstractAsynchronousTaggerProvider<TTag> { /// <summary> /// <para>The <see cref="TagSource"/> is the core part of our asynchronous /// tagging infrastructure. It is the coordinator between <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>s, /// <see cref="ITaggerEventSource"/>s, and <see cref="ITagger{T}"/>s.</para> /// /// <para>The <see cref="TagSource"/> is the type that actually owns the /// list of cached tags. When an <see cref="ITaggerEventSource"/> says tags need to be recomputed, /// the tag source starts the computation and calls <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> to build /// the new list of tags. When that's done, the tags are stored in <see cref="CachedTagTrees"/>. The /// tagger, when asked for tags from the editor, then returns the tags that are stored in /// <see cref="CachedTagTrees"/></para> /// /// <para>There is a one-to-many relationship between <see cref="TagSource"/>s /// and <see cref="ITagger{T}"/>s. Special cases, like reference highlighting (which processes multiple /// subject buffers at once) have their own providers and tag source derivations.</para> /// </summary> private sealed partial class TagSource : ForegroundThreadAffinitizedObject { /// <summary> /// If we get more than this many differences, then we just issue it as a single change /// notification. The number has been completely made up without any data to support it. /// /// Internal for testing purposes. /// </summary> private const int CoalesceDifferenceCount = 10; #region Fields that can be accessed from either thread private readonly AbstractAsynchronousTaggerProvider<TTag> _dataSource; /// <summary> /// async operation notifier /// </summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary> /// Work queue that collects high priority requests to call TagsChanged with. /// </summary> private readonly AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection> _highPriTagsChangedQueue; /// <summary> /// Work queue that collects normal priority requests to call TagsChanged with. /// </summary> private readonly AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection> _normalPriTagsChangedQueue; private readonly ReferenceCountedDisposable<TagSourceState> _tagSourceState = new(new TagSourceState()); #endregion #region Fields that can only be accessed from the foreground thread private readonly ITextView _textViewOpt; private readonly ITextBuffer _subjectBuffer; /// <summary> /// Our tagger event source that lets us know when we should call into the tag producer for /// new tags. /// </summary> private readonly ITaggerEventSource _eventSource; /// <summary> /// accumulated text changes since last tag calculation /// </summary> private TextChangeRange? _accumulatedTextChanges_doNotAccessDirectly; private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> _cachedTagTrees_doNotAccessDirectly = ImmutableDictionary.Create<ITextBuffer, TagSpanIntervalTree<TTag>>(); private object? _state_doNotAccessDirecty; /// <summary> /// Keep track of if we are processing the first <see cref="ITagger{T}.GetTags"/> request. If our provider returns /// <see langword="true"/> for <see cref="AbstractAsynchronousTaggerProvider{TTag}.ComputeInitialTagsSynchronously"/>, /// then we'll want to synchronously block then and only then for tags. /// </summary> private bool _firstTagsRequest = true; #endregion public TagSource( ITextView textViewOpt, ITextBuffer subjectBuffer, AbstractAsynchronousTaggerProvider<TTag> dataSource, IAsynchronousOperationListener asyncListener) : base(dataSource.ThreadingContext) { this.AssertIsForeground(); if (dataSource.SpanTrackingMode == SpanTrackingMode.Custom) throw new ArgumentException("SpanTrackingMode.Custom not allowed.", "spanTrackingMode"); _subjectBuffer = subjectBuffer; _textViewOpt = textViewOpt; _dataSource = dataSource; _asyncListener = asyncListener; _highPriTagsChangedQueue = new AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection>( TaggerDelay.NearImmediate.ComputeTimeDelay(), ProcessTagsChangedAsync, equalityComparer: null, asyncListener, _tagSourceState.Target.DisposalToken); if (_dataSource.AddedTagNotificationDelay == TaggerDelay.NearImmediate) { // if the tagger wants "added tags" to be reported "NearImmediate"ly, then just reuse // the "high pri" queue as that already reports things at that cadence. _normalPriTagsChangedQueue = _highPriTagsChangedQueue; } else { _normalPriTagsChangedQueue = new AsyncBatchingWorkQueue<NormalizedSnapshotSpanCollection>( _dataSource.AddedTagNotificationDelay.ComputeTimeDelay(), ProcessTagsChangedAsync, equalityComparer: null, asyncListener, _tagSourceState.Target.DisposalToken); } DebugRecordInitialStackTrace(); _eventSource = CreateEventSource(); Connect(); // Start computing the initial set of tags immediately. We want to get the UI // to a complete state as soon as possible. EnqueueWork(initialTags: true); return; void Connect() { this.AssertIsForeground(); _eventSource.Changed += OnEventSourceChanged; if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges)) { _subjectBuffer.Changed += OnSubjectBufferChanged; } if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag)) { if (_textViewOpt == null) { throw new ArgumentException( nameof(_dataSource.CaretChangeBehavior) + " can only be specified for an " + nameof(IViewTaggerProvider)); } _textViewOpt.Caret.PositionChanged += OnCaretPositionChanged; } // Tell the interaction object to start issuing events. _eventSource.Connect(); } } private void Dispose() { _tagSourceState.Dispose(); _dataSource.RemoveTagSource(_textViewOpt, _subjectBuffer); GC.SuppressFinalize(this); Disconnect(); return; void Disconnect() { this.AssertIsForeground(); // Tell the interaction object to stop issuing events. _eventSource.Disconnect(); if (_dataSource.CaretChangeBehavior.HasFlag(TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag)) { _textViewOpt.Caret.PositionChanged -= OnCaretPositionChanged; } if (_dataSource.TextChangeBehavior.HasFlag(TaggerTextChangeBehavior.TrackTextChanges)) { _subjectBuffer.Changed -= OnSubjectBufferChanged; } _eventSource.Changed -= OnEventSourceChanged; } } private ITaggerEventSource CreateEventSource() { var eventSource = _dataSource.CreateEventSource(_textViewOpt, _subjectBuffer); // If there are any options specified for this tagger, then also hook up event // notifications for when those options change. var optionChangedEventSources = _dataSource.Options.Concat<IOption>(_dataSource.PerLanguageOptions) .Select(o => TaggerEventSources.OnOptionChanged(_subjectBuffer, o)).ToList(); if (optionChangedEventSources.Count == 0) { // No options specified for this tagger. So just keep the event source as is. return eventSource; } optionChangedEventSources.Add(eventSource); return TaggerEventSources.Compose(optionChangedEventSources); } private TextChangeRange? AccumulatedTextChanges { get { this.AssertIsForeground(); return _accumulatedTextChanges_doNotAccessDirectly; } set { this.AssertIsForeground(); _accumulatedTextChanges_doNotAccessDirectly = value; } } private ImmutableDictionary<ITextBuffer, TagSpanIntervalTree<TTag>> CachedTagTrees { get { this.AssertIsForeground(); return _cachedTagTrees_doNotAccessDirectly; } set { this.AssertIsForeground(); _cachedTagTrees_doNotAccessDirectly = value; } } private object? State { get { this.AssertIsForeground(); return _state_doNotAccessDirecty; } set { this.AssertIsForeground(); _state_doNotAccessDirecty = value; } } private void RaiseTagsChanged(ITextBuffer buffer, DiffResult difference) { this.AssertIsForeground(); if (difference.Count == 0) { // nothing changed. return; } OnTagsChangedForBuffer(SpecializedCollections.SingletonCollection( new KeyValuePair<ITextBuffer, DiffResult>(buffer, difference)), initialTags: false); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used for finding <see cref="IWorkspaceService"/> and <see cref="IWorkspaceServiceFactory"/> exports. /// </summary> internal class WorkspaceServiceMetadata { public string ServiceType { get; } public string Layer { get; } public WorkspaceServiceMetadata(Type serviceType, string layer) : this(serviceType.AssemblyQualifiedName, layer) { } public WorkspaceServiceMetadata(IDictionary<string, object> data) { this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); this.Layer = (string)data.GetValueOrDefault("Layer"); } public WorkspaceServiceMetadata(string serviceType, string layer) { this.ServiceType = serviceType; this.Layer = layer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used for finding <see cref="IWorkspaceService"/> and <see cref="IWorkspaceServiceFactory"/> exports. /// </summary> internal class WorkspaceServiceMetadata { public string ServiceType { get; } public string Layer { get; } public WorkspaceServiceMetadata(Type serviceType, string layer) : this(serviceType.AssemblyQualifiedName, layer) { } public WorkspaceServiceMetadata(IDictionary<string, object> data) { this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); this.Layer = (string)data.GetValueOrDefault("Layer"); } public WorkspaceServiceMetadata(string serviceType, string layer) { this.ServiceType = serviceType; this.Layer = layer; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/Records/SynthesizedRecordEqualityOperator.cs
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols { /// <summary> /// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows: /// /// For record class: /// public static bool operator==(R? left, R? right) /// => (object) left == right || ((object)left != null &amp;&amp; left.Equals(right)); /// public static bool operator !=(R? left, R? right) /// => !(left == right); /// /// For record struct: /// public static bool operator==(R left, R right) /// => left.Equals(right); /// public static bool operator !=(R left, R right) /// => !(left == right); /// ///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>). ///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly. /// </summary> internal sealed class SynthesizedRecordEqualityOperator : SynthesizedRecordEqualityOperatorBase { public SynthesizedRecordEqualityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.EqualityOperatorName, memberOffset, diagnostics) { } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { // For record class: // => (object)left == right || ((object)left != null && left.Equals(right)); // For record struct: // => left.Equals(right)); MethodSymbol? equals = null; foreach (var member in ContainingType.GetMembers(WellKnownMemberNames.ObjectEquals)) { if (member is MethodSymbol candidate && candidate.ParameterCount == 1 && candidate.Parameters[0].RefKind == RefKind.None && candidate.ReturnType.SpecialType == SpecialType.System_Boolean && !candidate.IsStatic && candidate.Parameters[0].Type.Equals(ContainingType, TypeCompareKind.AllIgnoreOptions)) { equals = candidate; break; } } if (equals is null) { // Unable to locate expected method, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var left = F.Parameter(Parameters[0]); var right = F.Parameter(Parameters[1]); BoundExpression expression; if (ContainingType.IsRecordStruct) { expression = F.Call(left, equals, right); } else { BoundExpression objectEqual = F.ObjectEqual(left, right); BoundExpression recordEquals = F.LogicalAnd(F.ObjectNotEqual(left, F.Null(F.SpecialType(SpecialType.System_Object))), F.Call(left, equals, right)); expression = F.LogicalOr(objectEqual, recordEquals); } F.CloseMethod(F.Block(F.Return(expression))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Symbols { /// <summary> /// The record type includes synthesized '==' and '!=' operators equivalent to operators declared as follows: /// /// For record class: /// public static bool operator==(R? left, R? right) /// => (object) left == right || ((object)left != null &amp;&amp; left.Equals(right)); /// public static bool operator !=(R? left, R? right) /// => !(left == right); /// /// For record struct: /// public static bool operator==(R left, R right) /// => left.Equals(right); /// public static bool operator !=(R left, R right) /// => !(left == right); /// ///The 'Equals' method called by the '==' operator is the 'Equals(R? other)' (<see cref="SynthesizedRecordEquals"/>). ///The '!=' operator delegates to the '==' operator. It is an error if the operators are declared explicitly. /// </summary> internal sealed class SynthesizedRecordEqualityOperator : SynthesizedRecordEqualityOperatorBase { public SynthesizedRecordEqualityOperator(SourceMemberContainerTypeSymbol containingType, int memberOffset, BindingDiagnosticBag diagnostics) : base(containingType, WellKnownMemberNames.EqualityOperatorName, memberOffset, diagnostics) { } internal override void GenerateMethodBody(TypeCompilationState compilationState, BindingDiagnosticBag diagnostics) { var F = new SyntheticBoundNodeFactory(this, ContainingType.GetNonNullSyntaxNode(), compilationState, diagnostics); try { // For record class: // => (object)left == right || ((object)left != null && left.Equals(right)); // For record struct: // => left.Equals(right)); MethodSymbol? equals = null; foreach (var member in ContainingType.GetMembers(WellKnownMemberNames.ObjectEquals)) { if (member is MethodSymbol candidate && candidate.ParameterCount == 1 && candidate.Parameters[0].RefKind == RefKind.None && candidate.ReturnType.SpecialType == SpecialType.System_Boolean && !candidate.IsStatic && candidate.Parameters[0].Type.Equals(ContainingType, TypeCompareKind.AllIgnoreOptions)) { equals = candidate; break; } } if (equals is null) { // Unable to locate expected method, an error was reported elsewhere F.CloseMethod(F.ThrowNull()); return; } var left = F.Parameter(Parameters[0]); var right = F.Parameter(Parameters[1]); BoundExpression expression; if (ContainingType.IsRecordStruct) { expression = F.Call(left, equals, right); } else { BoundExpression objectEqual = F.ObjectEqual(left, right); BoundExpression recordEquals = F.LogicalAnd(F.ObjectNotEqual(left, F.Null(F.SpecialType(SpecialType.System_Object))), F.Call(left, equals, right)); expression = F.LogicalOr(objectEqual, recordEquals); } F.CloseMethod(F.Block(F.Return(expression))); } catch (SyntheticBoundNodeFactory.MissingPredefinedMember ex) { diagnostics.Add(ex.Diagnostic); F.CloseMethod(F.ThrowNull()); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Cocoa/Snippets/CSharpSnippets/SnippetFunctions/SnippetFunctionClassName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionClassName : AbstractSnippetFunctionClassName { public SnippetFunctionClassName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName) : base(snippetExpansionClient, subjectBuffer, fieldName) { } protected override void GetContainingClassName(Document document, SnapshotSpan fieldSpan, CancellationToken cancellationToken, ref string value, ref bool hasDefaultValue) { // Find the nearest enclosing type declaration and use its name var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var type = syntaxTree.FindTokenOnLeftOfPosition(fieldSpan.Start.Position, cancellationToken).GetAncestor<TypeDeclarationSyntax>(); if (type != null) { value = type.Identifier.ToString(); if (!string.IsNullOrWhiteSpace(value)) { hasDefaultValue = 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.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionClassName : AbstractSnippetFunctionClassName { public SnippetFunctionClassName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName) : base(snippetExpansionClient, subjectBuffer, fieldName) { } protected override void GetContainingClassName(Document document, SnapshotSpan fieldSpan, CancellationToken cancellationToken, ref string value, ref bool hasDefaultValue) { // Find the nearest enclosing type declaration and use its name var syntaxTree = document.GetRequiredSyntaxTreeSynchronously(cancellationToken); var type = syntaxTree.FindTokenOnLeftOfPosition(fieldSpan.Start.Position, cancellationToken).GetAncestor<TypeDeclarationSyntax>(); if (type != null) { value = type.Identifier.ToString(); if (!string.IsNullOrWhiteSpace(value)) { hasDefaultValue = true; } } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/WorkspaceDiagnosticEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis { public class WorkspaceDiagnosticEventArgs : EventArgs { public WorkspaceDiagnostic Diagnostic { get; } public WorkspaceDiagnosticEventArgs(WorkspaceDiagnostic diagnostic) => this.Diagnostic = diagnostic; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis { public class WorkspaceDiagnosticEventArgs : EventArgs { public WorkspaceDiagnostic Diagnostic { get; } public WorkspaceDiagnosticEventArgs(WorkspaceDiagnostic diagnostic) => this.Diagnostic = diagnostic; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/SignatureHelp/ConditionalExpressionSignatureHelpProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Friend MustInherit Class ConditionalExpressionSignatureHelpProvider(Of T As SyntaxNode) Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of T) Protected MustOverride ReadOnly Property Kind As SyntaxKind Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As T, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New BinaryConditionalExpressionDocumentation(), New TernaryConditionalExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) AndAlso token.Parent.Kind = Kind End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As T, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso (token.Kind <> SyntaxKind.CloseParenToken OrElse token.Parent.Kind <> Kind) End Function End Class <ExportSignatureHelpProvider("BinaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class BinaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of BinaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.BinaryConditionalExpression End Get End Property End Class <ExportSignatureHelpProvider("TernaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class TernaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of TernaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.TernaryConditionalExpression End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Friend MustInherit Class ConditionalExpressionSignatureHelpProvider(Of T As SyntaxNode) Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of T) Protected MustOverride ReadOnly Property Kind As SyntaxKind Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As T, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return ValueTaskFactory.FromResult(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New BinaryConditionalExpressionDocumentation(), New TernaryConditionalExpressionDocumentation()}) End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken) AndAlso token.Parent.Kind = Kind End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c OrElse ch = ","c End Function Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Protected Overrides Function IsArgumentListToken(node As T, token As SyntaxToken) As Boolean Return node.Span.Contains(token.SpanStart) AndAlso (token.Kind <> SyntaxKind.CloseParenToken OrElse token.Parent.Kind <> Kind) End Function End Class <ExportSignatureHelpProvider("BinaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class BinaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of BinaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.BinaryConditionalExpression End Get End Property End Class <ExportSignatureHelpProvider("TernaryConditionalExpressionSignatureHelpProvider", LanguageNames.VisualBasic), [Shared]> Friend Class TernaryConditionalExpressionSignatureHelpProvider Inherits ConditionalExpressionSignatureHelpProvider(Of TernaryConditionalExpressionSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property Kind As SyntaxKind Get Return SyntaxKind.TernaryConditionalExpression End Get End Property End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Interactive/Host/Interactive/Core/InteractiveHost.ShadowCopyReference.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { /// <summary> /// Specialize <see cref="PortableExecutableReference"/> with path being the original path of the copy. /// Logically this reference represents that file, the fact that we load the image from a copy is an implementation detail. /// </summary> private sealed class ShadowCopyReference : PortableExecutableReference { private readonly MetadataShadowCopyProvider _provider; public ShadowCopyReference(MetadataShadowCopyProvider provider, string originalPath, MetadataReferenceProperties properties) : base(properties, originalPath) { _provider = provider; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO (tomat): use file next to the dll (or shadow copy) return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { return _provider.GetMetadata(FilePath, Properties.Kind); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { return new ShadowCopyReference(_provider, FilePath!, 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. using Microsoft.CodeAnalysis.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Interactive { internal partial class InteractiveHost { /// <summary> /// Specialize <see cref="PortableExecutableReference"/> with path being the original path of the copy. /// Logically this reference represents that file, the fact that we load the image from a copy is an implementation detail. /// </summary> private sealed class ShadowCopyReference : PortableExecutableReference { private readonly MetadataShadowCopyProvider _provider; public ShadowCopyReference(MetadataShadowCopyProvider provider, string originalPath, MetadataReferenceProperties properties) : base(properties, originalPath) { _provider = provider; } protected override DocumentationProvider CreateDocumentationProvider() { // TODO (tomat): use file next to the dll (or shadow copy) return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { return _provider.GetMetadata(FilePath, Properties.Kind); } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { return new ShadowCopyReference(_provider, FilePath!, properties); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/VisualBasic/Portable/CodeGeneration/ExpressionGenerator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Partial Friend Module ExpressionGenerator Private Const s_doubleQuote = """" Friend Function GenerateExpression(typedConstant As TypedConstant) As ExpressionSyntax Select Case typedConstant.Kind Case TypedConstantKind.Primitive, TypedConstantKind.Enum Return GenerateExpression(typedConstant.Type, typedConstant.Value, canUseFieldReference:=True) Case TypedConstantKind.Array If typedConstant.IsNull Then Return GenerateNothingLiteral() Else Return SyntaxFactory.CollectionInitializer( SyntaxFactory.SeparatedList(typedConstant.Values.Select(AddressOf GenerateExpression))) End If Case TypedConstantKind.Type If Not TypeOf typedConstant.Value Is ITypeSymbol Then Return GenerateNothingLiteral() End If Return SyntaxFactory.GetTypeExpression(DirectCast(typedConstant.Value, ITypeSymbol).GenerateTypeSyntax()) Case Else Return GenerateNothingLiteral() End Select End Function Friend Function GenerateExpression(type As ITypeSymbol, value As Object, canUseFieldReference As Boolean) As ExpressionSyntax If (type.OriginalDefinition.SpecialType = SpecialType.System_Nullable_T) AndAlso (value IsNot Nothing) Then ' If the type of the argument is T?, then the type of the supplied default value can either be T ' (e.g. Optional x As Integer? = 5) or it can be T? (e.g. Optional x as SomeStruct? = Nothing). The ' below statement handles the case where the type of the supplied default value is T. Return GenerateExpression(DirectCast(type, INamedTypeSymbol).TypeArguments(0), value, canUseFieldReference) End If If type.TypeKind = TypeKind.Enum AndAlso value IsNot Nothing Then Return DirectCast(VisualBasicFlagsEnumGenerator.Instance.TryCreateEnumConstantValue(DirectCast(type, INamedTypeSymbol), value), ExpressionSyntax) End If Return GenerateNonEnumValueExpression(type, value, canUseFieldReference) End Function Friend Function GenerateNonEnumValueExpression(type As ITypeSymbol, value As Object, canUseFieldReference As Boolean) As ExpressionSyntax If TypeOf value Is Boolean Then Dim boolValue = DirectCast(value, Boolean) If boolValue Then Return SyntaxFactory.TrueLiteralExpression(SyntaxFactory.Token(SyntaxKind.TrueKeyword)) Else Return SyntaxFactory.FalseLiteralExpression(SyntaxFactory.Token(SyntaxKind.FalseKeyword)) End If ElseIf TypeOf value Is String Then Return GenerateStringLiteralExpression(type, DirectCast(value, String)) ElseIf TypeOf value Is Char Then Return GenerateCharLiteralExpression(DirectCast(value, Char)) ElseIf TypeOf value Is SByte Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_SByte, DirectCast(value, SByte), canUseFieldReference, LiteralSpecialValues.SByteSpecialValues, Function(x) x < 0, Function(x) -x, "128") ElseIf TypeOf value Is Short Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int16, DirectCast(value, Short), canUseFieldReference, LiteralSpecialValues.Int16SpecialValues, Function(x) x < 0, Function(x) -x, "32768") ElseIf TypeOf value Is Integer Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int32, DirectCast(value, Integer), canUseFieldReference, LiteralSpecialValues.Int32SpecialValues, Function(x) x < 0, Function(x) -x, "2147483648") ElseIf TypeOf value Is Long Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int64, DirectCast(value, Long), canUseFieldReference, LiteralSpecialValues.Int64SpecialValues, Function(x) x < 0, Function(x) -x, "9223372036854775808") ElseIf TypeOf value Is Byte Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_Byte, DirectCast(value, Byte), canUseFieldReference, LiteralSpecialValues.ByteSpecialValues) ElseIf TypeOf value Is UShort Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt16, DirectCast(value, UShort), canUseFieldReference, LiteralSpecialValues.UInt16SpecialValues) ElseIf TypeOf value Is UInteger Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt32, DirectCast(value, UInteger), canUseFieldReference, LiteralSpecialValues.UInt32SpecialValues) ElseIf TypeOf value Is ULong Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt64, DirectCast(value, ULong), canUseFieldReference, LiteralSpecialValues.UInt64SpecialValues) ElseIf TypeOf value Is Single Then Return GenerateSingleLiteralExpression(type, DirectCast(value, Single), canUseFieldReference) ElseIf TypeOf value Is Double Then Return GenerateDoubleLiteralExpression(type, DirectCast(value, Double), canUseFieldReference) ElseIf TypeOf value Is Decimal Then Return GenerateDecimalLiteralExpression(type, DirectCast(value, Decimal), canUseFieldReference) ElseIf TypeOf value Is DateTime Then Return GenerateDateLiteralExpression(DirectCast(value, DateTime)) Else Return GenerateNothingLiteral() End If End Function Private Function GenerateNothingLiteral() As ExpressionSyntax Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Private Function GenerateDateLiteralExpression(value As Date) As ExpressionSyntax Dim literal = SymbolDisplay.FormatPrimitive(value, quoteStrings:=False, useHexadecimalNumbers:=False) Return SyntaxFactory.DateLiteralExpression( SyntaxFactory.DateLiteralToken(literal, value)) End Function Private Function GenerateStringLiteralExpression(type As ITypeSymbol, value As String) As ExpressionSyntax Dim pieces = StringPiece.Split(value) If pieces.Count = 0 Then Return SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken(s_doubleQuote & s_doubleQuote, String.Empty)) End If If pieces.Count = 1 AndAlso pieces(0).Kind = StringPieceKind.NonPrintable Then If Not IsSpecialType(type, SpecialType.System_String) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CStrKeyword), pieces(0).GenerateExpression()) End If End If Dim expression As ExpressionSyntax = Nothing For Each piece In pieces Dim subExpression = piece.GenerateExpression() If expression Is Nothing Then expression = subExpression Else expression = SyntaxFactory.ConcatenateExpression(expression, subExpression) End If Next Return expression End Function Private Function GenerateMemberAccessExpression(ParamArray names As String()) As MemberAccessExpressionSyntax Dim expression As ExpressionSyntax = SyntaxFactory.GlobalName() For Each name In names expression = SyntaxFactory.SimpleMemberAccessExpression( expression, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(name)) Next Return DirectCast(expression, MemberAccessExpressionSyntax).WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function GenerateChrWExpression(c As Char) As InvocationExpressionSyntax Dim access = GenerateMemberAccessExpression("Microsoft", "VisualBasic", "Strings", "ChrW") Dim value = AscW(c) Dim argument = SyntaxFactory.SimpleArgument( SyntaxFactory.NumericLiteralExpression( SyntaxFactory.IntegerLiteralToken(value.ToString(Nothing, CultureInfo.InvariantCulture), LiteralBase.Decimal, TypeCharacter.None, CULng(value)))) Dim invocation = SyntaxFactory.InvocationExpression( access, SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)(argument))) Return invocation.WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function GenerateNonNegativeIntegralLiteralExpression(Of TStructure As IEquatable(Of TStructure))( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String))) As ExpressionSyntax Return GenerateIntegralLiteralExpression( type, specialType, value, canUseFieldReference, specialValues, Function(v) False, Function(v) Throw New InvalidOperationException() End Function, Nothing) End Function Private Function GenerateIntegralLiteralExpression(Of TStructure As IEquatable(Of TStructure))( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String)), isNegative As Func(Of TStructure, Boolean), negate As Func(Of TStructure, TStructure), integerMinValueString As String) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(specialType, value, specialValues) If field IsNot Nothing Then Return field End If End If Dim negative = isNegative(value) Dim nonNegativeValue = If(negative, negate(value), value) Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, nonNegativeValue, typeSuffix, suffix) Dim literal = If(negative AndAlso nonNegativeValue.Equals(value), integerMinValueString, DirectCast(nonNegativeValue, IFormattable).ToString(Nothing, CultureInfo.InvariantCulture) & suffix) Dim expression As ExpressionSyntax = SyntaxFactory.NumericLiteralExpression(SyntaxFactory.IntegerLiteralToken( literal, LiteralBase.Decimal, typeSuffix, IntegerUtilities.ToUInt64(nonNegativeValue))) If negative Then expression = SyntaxFactory.UnaryMinusExpression(expression) End If If TypeOf value Is Byte AndAlso Not IsSpecialType(type, SpecialType.System_Byte) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CByteKeyword), expression) ElseIf TypeOf value Is SByte AndAlso Not IsSpecialType(type, SpecialType.System_SByte) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CSByteKeyword), expression) End If Return expression End Function Private Sub DetermineSuffix(type As ITypeSymbol, value As Object, ByRef typeSuffix As TypeCharacter, ByRef suffix As String) If TypeOf value Is Short AndAlso Not IsSpecialType(type, SpecialType.System_Int16) Then typeSuffix = TypeCharacter.ShortLiteral suffix = "S" ElseIf TypeOf value Is Long AndAlso Not IsSpecialType(type, SpecialType.System_Int64) Then typeSuffix = TypeCharacter.LongLiteral suffix = "L" ElseIf TypeOf value Is Decimal Then Dim d = DirectCast(value, Decimal) Dim scale = d.GetScale() Dim typeIsNotDecimal = Not IsSpecialType(type, SpecialType.System_Decimal) Dim scaleIsNotZero = scale <> 0 Dim valueIsOutOfRange = d <= Long.MinValue OrElse d > Long.MaxValue If typeIsNotDecimal OrElse scaleIsNotZero OrElse valueIsOutOfRange Then typeSuffix = TypeCharacter.DecimalLiteral suffix = "D" End If ElseIf TypeOf value Is UShort AndAlso Not IsSpecialType(type, SpecialType.System_UInt16) Then typeSuffix = TypeCharacter.UShortLiteral suffix = "US" ElseIf TypeOf value Is UInteger AndAlso Not IsSpecialType(type, SpecialType.System_UInt32) Then typeSuffix = TypeCharacter.UIntegerLiteral suffix = "UI" ElseIf TypeOf value Is ULong Then Dim d = DirectCast(value, ULong) Dim typeIsNotULong = Not IsSpecialType(type, SpecialType.System_UInt64) Dim valueIsOutOfRange = d > Long.MaxValue If typeIsNotULong OrElse valueIsOutOfRange Then typeSuffix = TypeCharacter.ULongLiteral suffix = "UL" End If ElseIf TypeOf value Is Single AndAlso Not IsSpecialType(type, SpecialType.System_Single) Then typeSuffix = TypeCharacter.SingleLiteral suffix = "F" ElseIf TypeOf value Is Double AndAlso Not IsSpecialType(type, SpecialType.System_Double) Then typeSuffix = TypeCharacter.DoubleLiteral suffix = "R" End If End Sub Private Function GenerateDoubleLiteralExpression(type As ITypeSymbol, value As Double, canUseFieldReference As Boolean) As ExpressionSyntax If Not canUseFieldReference Then If Double.IsNaN(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(0.0, "0.0"), GenerateFloatLiteral(0.0, "0.0")) ElseIf Double.IsPositiveInfinity(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(1.0, "1.0"), GenerateFloatLiteral(0.0, "0.0")) ElseIf (Double.IsNegativeInfinity(value)) Then Return SyntaxFactory.DivideExpression( SyntaxFactory.UnaryMinusExpression(GenerateFloatLiteral(1.0, "1.0")), GenerateFloatLiteral(0.0, "0.0")) End If End If Return GenerateFloatLiteralExpression( type, SpecialType.System_Double, value, canUseFieldReference, LiteralSpecialValues.DoubleSpecialValues, Function(t) t < 0, Function(t) -t) End Function Private Function GenerateSingleLiteralExpression( type As ITypeSymbol, value As Single, canUseFieldReference As Boolean) As ExpressionSyntax If Not canUseFieldReference Then If Double.IsNaN(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(0.0, "0.0F"), GenerateFloatLiteral(0.0, "0.0F")) ElseIf Double.IsPositiveInfinity(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(1.0, "1.0F"), GenerateFloatLiteral(0.0, "0.0F")) ElseIf (Double.IsNegativeInfinity(value)) Then Return SyntaxFactory.DivideExpression( SyntaxFactory.UnaryMinusExpression(GenerateFloatLiteral(1.0, "1.0F")), GenerateFloatLiteral(0.0, "0.0F")) End If End If Return GenerateFloatLiteralExpression( type, SpecialType.System_Single, value, canUseFieldReference, LiteralSpecialValues.SingleSpecialValues, Function(t) t < 0, Function(t) -t) End Function Private Function GenerateFloatLiteralExpression(Of TStructure)( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String)), isNegative As Func(Of TStructure, Boolean), negate As Func(Of TStructure, TStructure)) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(specialType, value, specialValues) If field IsNot Nothing Then Return field End If End If Dim negative = isNegative(value) If negative Then value = negate(value) End If Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, value, typeSuffix, suffix) Dim literal = DirectCast(value, IFormattable).ToString("R", CultureInfo.InvariantCulture) & suffix Dim literalSyntax As ExpressionSyntax = GenerateFloatLiteral(Convert.ToDouble(value), literal, typeSuffix) Return If(negative, SyntaxFactory.UnaryMinusExpression(literalSyntax), literalSyntax) End Function Private Function GenerateFloatLiteral(value As Double, literal As String, Optional typeSuffix As TypeCharacter = TypeCharacter.None) As LiteralExpressionSyntax Return SyntaxFactory.NumericLiteralExpression(SyntaxFactory.FloatingLiteralToken( literal, typeSuffix, value)) End Function Private Function GenerateCharLiteralExpression(c As Char) As ExpressionSyntax Dim pieces = StringPiece.Split(c.ToString()) Dim piece = pieces(0) If piece.Kind = StringPieceKind.Normal Then Return SyntaxFactory.CharacterLiteralExpression(SyntaxFactory.CharacterLiteralToken( SymbolDisplay.FormatPrimitive(c, quoteStrings:=True, useHexadecimalNumbers:=False), c)) End If Return GenerateChrWExpression(c) End Function Private Function GenerateDecimalLiteralExpression(type As ITypeSymbol, value As Decimal, canUseFieldReference As Boolean) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(SpecialType.System_Decimal, value, LiteralSpecialValues.DecimalSpecialValues) If field IsNot Nothing Then Return field End If End If Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, value, typeSuffix, suffix) Dim literal = value.ToString(Nothing, CultureInfo.InvariantCulture) & suffix Return SyntaxFactory.NumericLiteralExpression(SyntaxFactory.DecimalLiteralToken(literal, typeSuffix, value)) End Function Private Function AddSpecialTypeAnnotation(type As SpecialType, expression As MemberAccessExpressionSyntax) As MemberAccessExpressionSyntax If SpecialType.None <> type Then Return expression.WithAdditionalAnnotations(SpecialTypeAnnotation.Create(type)) End If Return expression End Function Private Function GenerateFieldReference(Of TStructure)(type As SpecialType, value As Object, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String))) As MemberAccessExpressionSyntax For Each specialValue In specialValues If specialValue.Key.Equals(value) Then Dim memberAccess = AddSpecialTypeAnnotation(type, GenerateMemberAccessExpression("System", GetType(TStructure).Name)) Return SyntaxFactory.SimpleMemberAccessExpression(memberAccess, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(specialValue.Value)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Next Return Nothing End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Partial Friend Module ExpressionGenerator Private Const s_doubleQuote = """" Friend Function GenerateExpression(typedConstant As TypedConstant) As ExpressionSyntax Select Case typedConstant.Kind Case TypedConstantKind.Primitive, TypedConstantKind.Enum Return GenerateExpression(typedConstant.Type, typedConstant.Value, canUseFieldReference:=True) Case TypedConstantKind.Array If typedConstant.IsNull Then Return GenerateNothingLiteral() Else Return SyntaxFactory.CollectionInitializer( SyntaxFactory.SeparatedList(typedConstant.Values.Select(AddressOf GenerateExpression))) End If Case TypedConstantKind.Type If Not TypeOf typedConstant.Value Is ITypeSymbol Then Return GenerateNothingLiteral() End If Return SyntaxFactory.GetTypeExpression(DirectCast(typedConstant.Value, ITypeSymbol).GenerateTypeSyntax()) Case Else Return GenerateNothingLiteral() End Select End Function Friend Function GenerateExpression(type As ITypeSymbol, value As Object, canUseFieldReference As Boolean) As ExpressionSyntax If (type.OriginalDefinition.SpecialType = SpecialType.System_Nullable_T) AndAlso (value IsNot Nothing) Then ' If the type of the argument is T?, then the type of the supplied default value can either be T ' (e.g. Optional x As Integer? = 5) or it can be T? (e.g. Optional x as SomeStruct? = Nothing). The ' below statement handles the case where the type of the supplied default value is T. Return GenerateExpression(DirectCast(type, INamedTypeSymbol).TypeArguments(0), value, canUseFieldReference) End If If type.TypeKind = TypeKind.Enum AndAlso value IsNot Nothing Then Return DirectCast(VisualBasicFlagsEnumGenerator.Instance.TryCreateEnumConstantValue(DirectCast(type, INamedTypeSymbol), value), ExpressionSyntax) End If Return GenerateNonEnumValueExpression(type, value, canUseFieldReference) End Function Friend Function GenerateNonEnumValueExpression(type As ITypeSymbol, value As Object, canUseFieldReference As Boolean) As ExpressionSyntax If TypeOf value Is Boolean Then Dim boolValue = DirectCast(value, Boolean) If boolValue Then Return SyntaxFactory.TrueLiteralExpression(SyntaxFactory.Token(SyntaxKind.TrueKeyword)) Else Return SyntaxFactory.FalseLiteralExpression(SyntaxFactory.Token(SyntaxKind.FalseKeyword)) End If ElseIf TypeOf value Is String Then Return GenerateStringLiteralExpression(type, DirectCast(value, String)) ElseIf TypeOf value Is Char Then Return GenerateCharLiteralExpression(DirectCast(value, Char)) ElseIf TypeOf value Is SByte Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_SByte, DirectCast(value, SByte), canUseFieldReference, LiteralSpecialValues.SByteSpecialValues, Function(x) x < 0, Function(x) -x, "128") ElseIf TypeOf value Is Short Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int16, DirectCast(value, Short), canUseFieldReference, LiteralSpecialValues.Int16SpecialValues, Function(x) x < 0, Function(x) -x, "32768") ElseIf TypeOf value Is Integer Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int32, DirectCast(value, Integer), canUseFieldReference, LiteralSpecialValues.Int32SpecialValues, Function(x) x < 0, Function(x) -x, "2147483648") ElseIf TypeOf value Is Long Then Return GenerateIntegralLiteralExpression(type, SpecialType.System_Int64, DirectCast(value, Long), canUseFieldReference, LiteralSpecialValues.Int64SpecialValues, Function(x) x < 0, Function(x) -x, "9223372036854775808") ElseIf TypeOf value Is Byte Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_Byte, DirectCast(value, Byte), canUseFieldReference, LiteralSpecialValues.ByteSpecialValues) ElseIf TypeOf value Is UShort Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt16, DirectCast(value, UShort), canUseFieldReference, LiteralSpecialValues.UInt16SpecialValues) ElseIf TypeOf value Is UInteger Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt32, DirectCast(value, UInteger), canUseFieldReference, LiteralSpecialValues.UInt32SpecialValues) ElseIf TypeOf value Is ULong Then Return GenerateNonNegativeIntegralLiteralExpression(type, SpecialType.System_UInt64, DirectCast(value, ULong), canUseFieldReference, LiteralSpecialValues.UInt64SpecialValues) ElseIf TypeOf value Is Single Then Return GenerateSingleLiteralExpression(type, DirectCast(value, Single), canUseFieldReference) ElseIf TypeOf value Is Double Then Return GenerateDoubleLiteralExpression(type, DirectCast(value, Double), canUseFieldReference) ElseIf TypeOf value Is Decimal Then Return GenerateDecimalLiteralExpression(type, DirectCast(value, Decimal), canUseFieldReference) ElseIf TypeOf value Is DateTime Then Return GenerateDateLiteralExpression(DirectCast(value, DateTime)) Else Return GenerateNothingLiteral() End If End Function Private Function GenerateNothingLiteral() As ExpressionSyntax Return SyntaxFactory.NothingLiteralExpression(SyntaxFactory.Token(SyntaxKind.NothingKeyword)) End Function Private Function GenerateDateLiteralExpression(value As Date) As ExpressionSyntax Dim literal = SymbolDisplay.FormatPrimitive(value, quoteStrings:=False, useHexadecimalNumbers:=False) Return SyntaxFactory.DateLiteralExpression( SyntaxFactory.DateLiteralToken(literal, value)) End Function Private Function GenerateStringLiteralExpression(type As ITypeSymbol, value As String) As ExpressionSyntax Dim pieces = StringPiece.Split(value) If pieces.Count = 0 Then Return SyntaxFactory.StringLiteralExpression(SyntaxFactory.StringLiteralToken(s_doubleQuote & s_doubleQuote, String.Empty)) End If If pieces.Count = 1 AndAlso pieces(0).Kind = StringPieceKind.NonPrintable Then If Not IsSpecialType(type, SpecialType.System_String) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CStrKeyword), pieces(0).GenerateExpression()) End If End If Dim expression As ExpressionSyntax = Nothing For Each piece In pieces Dim subExpression = piece.GenerateExpression() If expression Is Nothing Then expression = subExpression Else expression = SyntaxFactory.ConcatenateExpression(expression, subExpression) End If Next Return expression End Function Private Function GenerateMemberAccessExpression(ParamArray names As String()) As MemberAccessExpressionSyntax Dim expression As ExpressionSyntax = SyntaxFactory.GlobalName() For Each name In names expression = SyntaxFactory.SimpleMemberAccessExpression( expression, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(name)) Next Return DirectCast(expression, MemberAccessExpressionSyntax).WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function GenerateChrWExpression(c As Char) As InvocationExpressionSyntax Dim access = GenerateMemberAccessExpression("Microsoft", "VisualBasic", "Strings", "ChrW") Dim value = AscW(c) Dim argument = SyntaxFactory.SimpleArgument( SyntaxFactory.NumericLiteralExpression( SyntaxFactory.IntegerLiteralToken(value.ToString(Nothing, CultureInfo.InvariantCulture), LiteralBase.Decimal, TypeCharacter.None, CULng(value)))) Dim invocation = SyntaxFactory.InvocationExpression( access, SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)(argument))) Return invocation.WithAdditionalAnnotations(Simplifier.Annotation) End Function Private Function GenerateNonNegativeIntegralLiteralExpression(Of TStructure As IEquatable(Of TStructure))( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String))) As ExpressionSyntax Return GenerateIntegralLiteralExpression( type, specialType, value, canUseFieldReference, specialValues, Function(v) False, Function(v) Throw New InvalidOperationException() End Function, Nothing) End Function Private Function GenerateIntegralLiteralExpression(Of TStructure As IEquatable(Of TStructure))( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String)), isNegative As Func(Of TStructure, Boolean), negate As Func(Of TStructure, TStructure), integerMinValueString As String) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(specialType, value, specialValues) If field IsNot Nothing Then Return field End If End If Dim negative = isNegative(value) Dim nonNegativeValue = If(negative, negate(value), value) Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, nonNegativeValue, typeSuffix, suffix) Dim literal = If(negative AndAlso nonNegativeValue.Equals(value), integerMinValueString, DirectCast(nonNegativeValue, IFormattable).ToString(Nothing, CultureInfo.InvariantCulture) & suffix) Dim expression As ExpressionSyntax = SyntaxFactory.NumericLiteralExpression(SyntaxFactory.IntegerLiteralToken( literal, LiteralBase.Decimal, typeSuffix, IntegerUtilities.ToUInt64(nonNegativeValue))) If negative Then expression = SyntaxFactory.UnaryMinusExpression(expression) End If If TypeOf value Is Byte AndAlso Not IsSpecialType(type, SpecialType.System_Byte) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CByteKeyword), expression) ElseIf TypeOf value Is SByte AndAlso Not IsSpecialType(type, SpecialType.System_SByte) Then Return SyntaxFactory.PredefinedCastExpression(SyntaxFactory.Token(SyntaxKind.CSByteKeyword), expression) End If Return expression End Function Private Sub DetermineSuffix(type As ITypeSymbol, value As Object, ByRef typeSuffix As TypeCharacter, ByRef suffix As String) If TypeOf value Is Short AndAlso Not IsSpecialType(type, SpecialType.System_Int16) Then typeSuffix = TypeCharacter.ShortLiteral suffix = "S" ElseIf TypeOf value Is Long AndAlso Not IsSpecialType(type, SpecialType.System_Int64) Then typeSuffix = TypeCharacter.LongLiteral suffix = "L" ElseIf TypeOf value Is Decimal Then Dim d = DirectCast(value, Decimal) Dim scale = d.GetScale() Dim typeIsNotDecimal = Not IsSpecialType(type, SpecialType.System_Decimal) Dim scaleIsNotZero = scale <> 0 Dim valueIsOutOfRange = d <= Long.MinValue OrElse d > Long.MaxValue If typeIsNotDecimal OrElse scaleIsNotZero OrElse valueIsOutOfRange Then typeSuffix = TypeCharacter.DecimalLiteral suffix = "D" End If ElseIf TypeOf value Is UShort AndAlso Not IsSpecialType(type, SpecialType.System_UInt16) Then typeSuffix = TypeCharacter.UShortLiteral suffix = "US" ElseIf TypeOf value Is UInteger AndAlso Not IsSpecialType(type, SpecialType.System_UInt32) Then typeSuffix = TypeCharacter.UIntegerLiteral suffix = "UI" ElseIf TypeOf value Is ULong Then Dim d = DirectCast(value, ULong) Dim typeIsNotULong = Not IsSpecialType(type, SpecialType.System_UInt64) Dim valueIsOutOfRange = d > Long.MaxValue If typeIsNotULong OrElse valueIsOutOfRange Then typeSuffix = TypeCharacter.ULongLiteral suffix = "UL" End If ElseIf TypeOf value Is Single AndAlso Not IsSpecialType(type, SpecialType.System_Single) Then typeSuffix = TypeCharacter.SingleLiteral suffix = "F" ElseIf TypeOf value Is Double AndAlso Not IsSpecialType(type, SpecialType.System_Double) Then typeSuffix = TypeCharacter.DoubleLiteral suffix = "R" End If End Sub Private Function GenerateDoubleLiteralExpression(type As ITypeSymbol, value As Double, canUseFieldReference As Boolean) As ExpressionSyntax If Not canUseFieldReference Then If Double.IsNaN(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(0.0, "0.0"), GenerateFloatLiteral(0.0, "0.0")) ElseIf Double.IsPositiveInfinity(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(1.0, "1.0"), GenerateFloatLiteral(0.0, "0.0")) ElseIf (Double.IsNegativeInfinity(value)) Then Return SyntaxFactory.DivideExpression( SyntaxFactory.UnaryMinusExpression(GenerateFloatLiteral(1.0, "1.0")), GenerateFloatLiteral(0.0, "0.0")) End If End If Return GenerateFloatLiteralExpression( type, SpecialType.System_Double, value, canUseFieldReference, LiteralSpecialValues.DoubleSpecialValues, Function(t) t < 0, Function(t) -t) End Function Private Function GenerateSingleLiteralExpression( type As ITypeSymbol, value As Single, canUseFieldReference As Boolean) As ExpressionSyntax If Not canUseFieldReference Then If Double.IsNaN(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(0.0, "0.0F"), GenerateFloatLiteral(0.0, "0.0F")) ElseIf Double.IsPositiveInfinity(value) Then Return SyntaxFactory.DivideExpression( GenerateFloatLiteral(1.0, "1.0F"), GenerateFloatLiteral(0.0, "0.0F")) ElseIf (Double.IsNegativeInfinity(value)) Then Return SyntaxFactory.DivideExpression( SyntaxFactory.UnaryMinusExpression(GenerateFloatLiteral(1.0, "1.0F")), GenerateFloatLiteral(0.0, "0.0F")) End If End If Return GenerateFloatLiteralExpression( type, SpecialType.System_Single, value, canUseFieldReference, LiteralSpecialValues.SingleSpecialValues, Function(t) t < 0, Function(t) -t) End Function Private Function GenerateFloatLiteralExpression(Of TStructure)( type As ITypeSymbol, specialType As SpecialType, value As TStructure, canUseFieldReference As Boolean, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String)), isNegative As Func(Of TStructure, Boolean), negate As Func(Of TStructure, TStructure)) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(specialType, value, specialValues) If field IsNot Nothing Then Return field End If End If Dim negative = isNegative(value) If negative Then value = negate(value) End If Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, value, typeSuffix, suffix) Dim literal = DirectCast(value, IFormattable).ToString("R", CultureInfo.InvariantCulture) & suffix Dim literalSyntax As ExpressionSyntax = GenerateFloatLiteral(Convert.ToDouble(value), literal, typeSuffix) Return If(negative, SyntaxFactory.UnaryMinusExpression(literalSyntax), literalSyntax) End Function Private Function GenerateFloatLiteral(value As Double, literal As String, Optional typeSuffix As TypeCharacter = TypeCharacter.None) As LiteralExpressionSyntax Return SyntaxFactory.NumericLiteralExpression(SyntaxFactory.FloatingLiteralToken( literal, typeSuffix, value)) End Function Private Function GenerateCharLiteralExpression(c As Char) As ExpressionSyntax Dim pieces = StringPiece.Split(c.ToString()) Dim piece = pieces(0) If piece.Kind = StringPieceKind.Normal Then Return SyntaxFactory.CharacterLiteralExpression(SyntaxFactory.CharacterLiteralToken( SymbolDisplay.FormatPrimitive(c, quoteStrings:=True, useHexadecimalNumbers:=False), c)) End If Return GenerateChrWExpression(c) End Function Private Function GenerateDecimalLiteralExpression(type As ITypeSymbol, value As Decimal, canUseFieldReference As Boolean) As ExpressionSyntax If canUseFieldReference Then Dim field = GenerateFieldReference(SpecialType.System_Decimal, value, LiteralSpecialValues.DecimalSpecialValues) If field IsNot Nothing Then Return field End If End If Dim typeSuffix As TypeCharacter = TypeCharacter.None Dim suffix As String = String.Empty DetermineSuffix(type, value, typeSuffix, suffix) Dim literal = value.ToString(Nothing, CultureInfo.InvariantCulture) & suffix Return SyntaxFactory.NumericLiteralExpression(SyntaxFactory.DecimalLiteralToken(literal, typeSuffix, value)) End Function Private Function AddSpecialTypeAnnotation(type As SpecialType, expression As MemberAccessExpressionSyntax) As MemberAccessExpressionSyntax If SpecialType.None <> type Then Return expression.WithAdditionalAnnotations(SpecialTypeAnnotation.Create(type)) End If Return expression End Function Private Function GenerateFieldReference(Of TStructure)(type As SpecialType, value As Object, specialValues As IEnumerable(Of KeyValuePair(Of TStructure, String))) As MemberAccessExpressionSyntax For Each specialValue In specialValues If specialValue.Key.Equals(value) Then Dim memberAccess = AddSpecialTypeAnnotation(type, GenerateMemberAccessExpression("System", GetType(TStructure).Name)) Return SyntaxFactory.SimpleMemberAccessExpression(memberAccess, SyntaxFactory.Token(SyntaxKind.DotToken), SyntaxFactory.IdentifierName(specialValue.Value)) _ .WithAdditionalAnnotations(Simplifier.Annotation) End If Next Return Nothing End Function End Module End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/HACK_ThemeColorFixer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ObjectModel; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// This class works around the fact that shell theme changes are not fully propagated into an /// editor classification format map unless a classification type is registered as a font and /// color item in that format map's font and color category. So, for example, the "Keyword" /// classification type in the "tooltip" classification format map is never is never updated /// from its default blue. As a work around, we listen to <see cref="IClassificationFormatMap.ClassificationFormatMappingChanged"/> /// and update the classification format maps that we care about. /// </summary> [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.RoslynContentType)] [TextViewRole(PredefinedTextViewRoles.Analyzable)] internal sealed class HACK_ThemeColorFixer : IWpfTextViewConnectionListener { private readonly IClassificationTypeRegistryService _classificationTypeRegistryService; private readonly IClassificationFormatMapService _classificationFormatMapService; private bool _done; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HACK_ThemeColorFixer( IClassificationTypeRegistryService classificationTypeRegistryService, IClassificationFormatMapService classificationFormatMapService) { _classificationTypeRegistryService = classificationTypeRegistryService; _classificationFormatMapService = classificationFormatMapService; // Note: We never unsubscribe from this event. This service lives for the lifetime of VS. _classificationFormatMapService.GetClassificationFormatMap("text").ClassificationFormatMappingChanged += TextFormatMap_ClassificationFormatMappingChanged; } private void TextFormatMap_ClassificationFormatMappingChanged(object sender, EventArgs e) => VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors); public void RefreshThemeColors() { var textFormatMap = _classificationFormatMapService.GetClassificationFormatMap("text"); var tooltipFormatMap = _classificationFormatMapService.GetClassificationFormatMap("tooltip"); UpdateForegroundColors(textFormatMap, tooltipFormatMap); } private void UpdateForegroundColors( IClassificationFormatMap sourceFormatMap, IClassificationFormatMap targetFormatMap) { UpdateForegroundColor(ClassificationTypeNames.Comment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ExcludedCode, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Identifier, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Keyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ControlKeyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.NumericLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StringLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeQuotes, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeValue, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentDelimiter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentCDataSection, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexCharacterClass, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexQuantifier, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexAnchor, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexAlternation, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexGrouping, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexOtherEscape, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexSelfEscapedCharacter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PreprocessorKeyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PreprocessorText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Operator, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.OperatorOverloaded, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Punctuation, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ClassName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RecordClassName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StructName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.InterfaceName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.DelegateName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EnumName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.TypeParameterName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ModuleName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.FieldName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EnumMemberName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ConstantName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.LocalName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ParameterName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.MethodName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ExtensionMethodName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PropertyName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EventName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.NamespaceName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.LabelName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.VerbatimStringLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StringEscapeCharacter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralProcessingInstruction, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEmbeddedExpression, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralDelimiter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralCDataSection, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeValue, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeQuotes, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEntityReference, sourceFormatMap, targetFormatMap); } private void UpdateForegroundColor( string classificationTypeName, IClassificationFormatMap sourceFormatMap, IClassificationFormatMap targetFormatMap) { var classificationType = _classificationTypeRegistryService.GetClassificationType(classificationTypeName); if (classificationType == null) { return; } var sourceProps = sourceFormatMap.GetTextProperties(classificationType); var targetProps = targetFormatMap.GetTextProperties(classificationType); targetProps = targetProps.SetForegroundBrush(sourceProps.ForegroundBrush); targetFormatMap.SetTextProperties(classificationType, targetProps); } public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { // DevDiv https://devdiv.visualstudio.com/DevDiv/_workitems/edit/130129: // // This needs to be scheduled after editor has been composed. Otherwise // it may cause UI delays by composing the editor before it is needed // by the rest of VS. if (!_done) { _done = true; VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors); } } public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ObjectModel; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices { /// <summary> /// This class works around the fact that shell theme changes are not fully propagated into an /// editor classification format map unless a classification type is registered as a font and /// color item in that format map's font and color category. So, for example, the "Keyword" /// classification type in the "tooltip" classification format map is never is never updated /// from its default blue. As a work around, we listen to <see cref="IClassificationFormatMap.ClassificationFormatMappingChanged"/> /// and update the classification format maps that we care about. /// </summary> [Export(typeof(IWpfTextViewConnectionListener))] [ContentType(ContentTypeNames.RoslynContentType)] [TextViewRole(PredefinedTextViewRoles.Analyzable)] internal sealed class HACK_ThemeColorFixer : IWpfTextViewConnectionListener { private readonly IClassificationTypeRegistryService _classificationTypeRegistryService; private readonly IClassificationFormatMapService _classificationFormatMapService; private bool _done; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public HACK_ThemeColorFixer( IClassificationTypeRegistryService classificationTypeRegistryService, IClassificationFormatMapService classificationFormatMapService) { _classificationTypeRegistryService = classificationTypeRegistryService; _classificationFormatMapService = classificationFormatMapService; // Note: We never unsubscribe from this event. This service lives for the lifetime of VS. _classificationFormatMapService.GetClassificationFormatMap("text").ClassificationFormatMappingChanged += TextFormatMap_ClassificationFormatMappingChanged; } private void TextFormatMap_ClassificationFormatMappingChanged(object sender, EventArgs e) => VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors); public void RefreshThemeColors() { var textFormatMap = _classificationFormatMapService.GetClassificationFormatMap("text"); var tooltipFormatMap = _classificationFormatMapService.GetClassificationFormatMap("tooltip"); UpdateForegroundColors(textFormatMap, tooltipFormatMap); } private void UpdateForegroundColors( IClassificationFormatMap sourceFormatMap, IClassificationFormatMap targetFormatMap) { UpdateForegroundColor(ClassificationTypeNames.Comment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ExcludedCode, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Identifier, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Keyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ControlKeyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.NumericLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StringLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeQuotes, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentAttributeValue, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentDelimiter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlDocCommentCDataSection, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexCharacterClass, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexQuantifier, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexAnchor, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexAlternation, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexGrouping, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexOtherEscape, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RegexSelfEscapedCharacter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PreprocessorKeyword, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PreprocessorText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Operator, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.OperatorOverloaded, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.Punctuation, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ClassName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.RecordClassName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StructName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.InterfaceName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.DelegateName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EnumName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.TypeParameterName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ModuleName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.FieldName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EnumMemberName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ConstantName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.LocalName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ParameterName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.MethodName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.ExtensionMethodName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.PropertyName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.EventName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.NamespaceName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.LabelName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.VerbatimStringLiteral, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.StringEscapeCharacter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralText, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralProcessingInstruction, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEmbeddedExpression, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralDelimiter, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralComment, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralCDataSection, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeValue, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeQuotes, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralAttributeName, sourceFormatMap, targetFormatMap); UpdateForegroundColor(ClassificationTypeNames.XmlLiteralEntityReference, sourceFormatMap, targetFormatMap); } private void UpdateForegroundColor( string classificationTypeName, IClassificationFormatMap sourceFormatMap, IClassificationFormatMap targetFormatMap) { var classificationType = _classificationTypeRegistryService.GetClassificationType(classificationTypeName); if (classificationType == null) { return; } var sourceProps = sourceFormatMap.GetTextProperties(classificationType); var targetProps = targetFormatMap.GetTextProperties(classificationType); targetProps = targetProps.SetForegroundBrush(sourceProps.ForegroundBrush); targetFormatMap.SetTextProperties(classificationType, targetProps); } public void SubjectBuffersConnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { // DevDiv https://devdiv.visualstudio.com/DevDiv/_workitems/edit/130129: // // This needs to be scheduled after editor has been composed. Otherwise // it may cause UI delays by composing the editor before it is needed // by the rest of VS. if (!_done) { _done = true; VsTaskLibraryHelper.CreateAndStartTask(VsTaskLibraryHelper.ServiceInstance, VsTaskRunContext.UIThreadIdlePriority, RefreshThemeColors); } } public void SubjectBuffersDisconnected(IWpfTextView textView, ConnectionReason reason, Collection<ITextBuffer> subjectBuffers) { } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/Resources/NetCoreApp2AndTwoLibraries/Library1.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.DelegateInvokeMethodSymbols.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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(11003, "DevDiv_Projects/Roslyn")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAnonymousDelegateInvoke1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function Main(args As String()) Dim q = {|Definition:Function(e As Integer) Return True End Function|}.$$[|Invoke|](42) Dim r = Function(e2 As Integer) Return True End Function.[|Invoke|](42) End Function End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) 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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WorkItem(11003, "DevDiv_Projects/Roslyn")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestAnonymousDelegateInvoke1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Function Main(args As String()) Dim q = {|Definition:Function(e As Integer) Return True End Function|}.$$[|Invoke|](42) Dim r = Function(e2 As Integer) Return True End Function.[|Invoke|](42) End Function End Module </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/CodeLens/ICodeLensContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeLens; using Microsoft.VisualStudio.Language.CodeLens; using Microsoft.VisualStudio.Language.CodeLens.Remoting; namespace Microsoft.VisualStudio.LanguageServices.CodeLens { /// <summary> /// Provide information related to VS/Roslyn to CodeLens OOP process /// </summary> internal interface ICodeLensContext { Task<ImmutableDictionary<Guid, string>> GetProjectVersionsAsync(ImmutableArray<Guid> projectGuids, CancellationToken cancellationToken); /// <summary> /// Get reference count of the given descriptor /// </summary> Task<ReferenceCount?> GetReferenceCountAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, ReferenceCount? previousCount, CancellationToken cancellationToken); /// <summary> /// get reference location descriptor of the given descriptor /// </summary> Task<(string projectVersion, ImmutableArray<ReferenceLocationDescriptor> references)?> FindReferenceLocationsAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeLens; using Microsoft.VisualStudio.Language.CodeLens; using Microsoft.VisualStudio.Language.CodeLens.Remoting; namespace Microsoft.VisualStudio.LanguageServices.CodeLens { /// <summary> /// Provide information related to VS/Roslyn to CodeLens OOP process /// </summary> internal interface ICodeLensContext { Task<ImmutableDictionary<Guid, string>> GetProjectVersionsAsync(ImmutableArray<Guid> projectGuids, CancellationToken cancellationToken); /// <summary> /// Get reference count of the given descriptor /// </summary> Task<ReferenceCount?> GetReferenceCountAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, ReferenceCount? previousCount, CancellationToken cancellationToken); /// <summary> /// get reference location descriptor of the given descriptor /// </summary> Task<(string projectVersion, ImmutableArray<ReferenceLocationDescriptor> references)?> FindReferenceLocationsAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync( CodeLensDescriptor descriptor, CodeLensDescriptorContext descriptorContext, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/VSTypeScriptIndentationResultWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CS0618 // Type or member is obsolete (https://github.com/dotnet/roslyn/issues/35872) using Microsoft.CodeAnalysis.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptIndentationResultWrapper { private readonly IndentationResult _underlyingObject; public VSTypeScriptIndentationResultWrapper(IndentationResult underlyingObject) => _underlyingObject = underlyingObject; public int BasePosition => _underlyingObject.BasePosition; public int Offset => _underlyingObject.Offset; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable CS0618 // Type or member is obsolete (https://github.com/dotnet/roslyn/issues/35872) using Microsoft.CodeAnalysis.Editor; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptIndentationResultWrapper { private readonly IndentationResult _underlyingObject; public VSTypeScriptIndentationResultWrapper(IndentationResult underlyingObject) => _underlyingObject = underlyingObject; public int BasePosition => _underlyingObject.BasePosition; public int Offset => _underlyingObject.Offset; } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharp/BraceMatching/AbstractCSharpBraceMatcher.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { internal abstract class AbstractCSharpBraceMatcher : AbstractBraceMatcher { protected AbstractCSharpBraceMatcher(SyntaxKind openBrace, SyntaxKind closeBrace) : base(new BraceCharacterAndKind(SyntaxFacts.GetText(openBrace)[0], (int)openBrace), new BraceCharacterAndKind(SyntaxFacts.GetText(closeBrace)[0], (int)closeBrace)) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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; using Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching; namespace Microsoft.CodeAnalysis.Editor.CSharp.BraceMatching { internal abstract class AbstractCSharpBraceMatcher : AbstractBraceMatcher { protected AbstractCSharpBraceMatcher(SyntaxKind openBrace, SyntaxKind closeBrace) : base(new BraceCharacterAndKind(SyntaxFacts.GetText(openBrace)[0], (int)openBrace), new BraceCharacterAndKind(SyntaxFacts.GetText(closeBrace)[0], (int)closeBrace)) { } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PENamedTypeSymbolWithEmittedNamespaceName.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent top level types imported from a PE/module. ''' </summary> Friend NotInheritable Class PENamedTypeSymbolWithEmittedNamespaceName Inherits PENamedTypeSymbol Private ReadOnly _emittedNamespaceName As String Private ReadOnly _corTypeId As SpecialType Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, typeDef As TypeDefinitionHandle, emittedNamespaceName As String ) MyBase.New(moduleSymbol, containingNamespace, typeDef) Debug.Assert(emittedNamespaceName IsNot Nothing) Debug.Assert(emittedNamespaceName.Length > 0) _emittedNamespaceName = emittedNamespaceName ' check if this is one of the COR library types If (Arity = 0 OrElse MangleName) AndAlso (moduleSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) AndAlso Me.DeclaredAccessibility = Accessibility.Public Then Debug.Assert(emittedNamespaceName.Length > 0) _corTypeId = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(emittedNamespaceName, MetadataName)) Else _corTypeId = SpecialType.None End If End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _corTypeId End Get End Property Friend Overrides Function GetEmittedNamespaceName() As String Return _emittedNamespaceName End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent top level types imported from a PE/module. ''' </summary> Friend NotInheritable Class PENamedTypeSymbolWithEmittedNamespaceName Inherits PENamedTypeSymbol Private ReadOnly _emittedNamespaceName As String Private ReadOnly _corTypeId As SpecialType Friend Sub New( moduleSymbol As PEModuleSymbol, containingNamespace As PENamespaceSymbol, typeDef As TypeDefinitionHandle, emittedNamespaceName As String ) MyBase.New(moduleSymbol, containingNamespace, typeDef) Debug.Assert(emittedNamespaceName IsNot Nothing) Debug.Assert(emittedNamespaceName.Length > 0) _emittedNamespaceName = emittedNamespaceName ' check if this is one of the COR library types If (Arity = 0 OrElse MangleName) AndAlso (moduleSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) AndAlso Me.DeclaredAccessibility = Accessibility.Public Then Debug.Assert(emittedNamespaceName.Length > 0) _corTypeId = SpecialTypes.GetTypeFromMetadataName(MetadataHelpers.BuildQualifiedName(emittedNamespaceName, MetadataName)) Else _corTypeId = SpecialType.None End If End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _corTypeId End Get End Property Friend Overrides Function GetEmittedNamespaceName() As String Return _emittedNamespaceName End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/EntryPointsWalker.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is ''' invoked by a superclass when the two endpoints of a jump have been identified. ''' </summary> ''' <remarks></remarks> Friend Class EntryPointsWalker Inherits AbstractRegionControlFlowPass Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax) Dim walker = New EntryPointsWalker(info, region) Try succeeded = walker.Analyze() Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)()) Finally walker.Free() End Try End Function Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)() Private Overloads Function Analyze() As Boolean ' We only need to scan in a single pass. Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Protected Overrides Sub Free() MyBase.Free() End Sub Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement) If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then Select Case stmt.Kind Case BoundKind.GotoStatement _entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax)) Case BoundKind.ReturnStatement ' Do nothing Case Else Throw ExceptionUtilities.UnexpectedValue(stmt.Kind) End Select End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' A region analysis walker that records jumps into the region. Works by overriding NoteBranch, which is ''' invoked by a superclass when the two endpoints of a jump have been identified. ''' </summary> ''' <remarks></remarks> Friend Class EntryPointsWalker Inherits AbstractRegionControlFlowPass Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo, ByRef succeeded As Boolean?) As IEnumerable(Of LabelStatementSyntax) Dim walker = New EntryPointsWalker(info, region) Try succeeded = walker.Analyze() Return If(succeeded, walker._entryPoints, SpecializedCollections.EmptyEnumerable(Of LabelStatementSyntax)()) Finally walker.Free() End Try End Function Private ReadOnly _entryPoints As HashSet(Of LabelStatementSyntax) = New HashSet(Of LabelStatementSyntax)() Private Overloads Function Analyze() As Boolean ' We only need to scan in a single pass. Return Scan() End Function Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo) MyBase.New(info, region) End Sub Protected Overrides Sub Free() MyBase.Free() End Sub Protected Overrides Sub NoteBranch(pending As PendingBranch, stmt As BoundStatement, labelStmt As BoundLabelStatement) If stmt.Syntax IsNot Nothing AndAlso labelStmt.Syntax IsNot Nothing AndAlso IsInsideRegion(labelStmt.Syntax.Span) AndAlso Not IsInsideRegion(stmt.Syntax.Span) Then Select Case stmt.Kind Case BoundKind.GotoStatement _entryPoints.Add(DirectCast(labelStmt.Syntax, LabelStatementSyntax)) Case BoundKind.ReturnStatement ' Do nothing Case Else Throw ExceptionUtilities.UnexpectedValue(stmt.Kind) End Select End If End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Semantic/Semantics/InterpolatedStringTests.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.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InterpolatedStringTests Inherits BasicTestBase Private ReadOnly _formattableStringSource As Xml.Linq.XElement = <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return New ConcreteFormattableString(formatString, args) End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <Fact> Public Sub SimpleInterpolation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 8675309") End Sub <Fact> Public Sub InterpolationWithAlignment() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,12}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 8675309") End Sub <Fact> Public Sub InterpolationWithAlignmentWithNonDecimalBaseAndOrTypeSuffix() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,&amp;H1A} {1,1UL}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: " & "8675309".PadLeft(&H1A) & " 1") End Sub <Fact> Public Sub InterpolationWithFormat() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number:###-####}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 867-5309") End Sub <Fact> Public Sub InterpolationWithFormatAndAlignment() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,12:###-####}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 867-5309") End Sub <Fact> Public Sub TwoInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim Hello = "Goodbye", World = "No one" Write($"This is a ""{NameOf(Hello)}, {NameOf(World)}!"" program.") End Sub End Module </file> </compilation>, expectedOutput:="This is a ""Hello, World!"" program.") End Sub <Fact> Public Sub EscapeSequences() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim arr As Object() = {} Write($"Solution: {{ { If(arr.Length > 0, String.Join("", "", arr), "Ø") } }}") End Sub End Module </file> </compilation>, expectedOutput:="Solution: { Ø }") End Sub <Fact> Public Sub EscapeSequencesWitNoInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Write($"{{Ø}}") End Sub End Module </file> </compilation>, expectedOutput:="{Ø}") End Sub <Fact, WorkItem(1102783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1102783")> Public Sub SmartQuotes() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Sub Main() Dim arr = { $<%= LEFT_DOUBLE_QUOTATION_MARK %>1<%= RIGHT_DOUBLE_QUOTATION_MARK %>, $<%= RIGHT_DOUBLE_QUOTATION_MARK %>2<%= LEFT_DOUBLE_QUOTATION_MARK %>, $<%= LEFT_DOUBLE_QUOTATION_MARK %>3", $"4<%= LEFT_DOUBLE_QUOTATION_MARK %>, $"5<%= RIGHT_DOUBLE_QUOTATION_MARK %>, $<%= RIGHT_DOUBLE_QUOTATION_MARK %>6", $" <%= RIGHT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %> ", $<%= RIGHT_DOUBLE_QUOTATION_MARK %> {1:x<%= RIGHT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %>y} <%= LEFT_DOUBLE_QUOTATION_MARK %> } System.Console.WriteLine(String.Join("", arr)) End Sub End Module </file> </compilation>, expectedOutput:="123456 "" xy") End Sub <Fact, WorkItem(1102800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1102800")> Public Sub FullwidthDelimiters() ' Any combination of fullwidth and ASCII curly braces of the same direction is an escaping sequence for the corresponding ASCII curly brace. ' We insert that curly brace doubled and because this is the escaping sequence understood by String.Format, that will be replaced by a single brace. ' This is deliberate design and it aligns with existing rules for double quote escaping in strings. CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() WriteLine($"{0<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "0") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %>10<%= FULLWIDTH_COLON %>X}" = "A") WriteLine($"}}" = "}") WriteLine($"}<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "}") WriteLine($"<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>}" = "}") WriteLine($"<%= FULLWIDTH_RIGHT_CURLY_BRACKET %><%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "}") WriteLine($"{{" = "{") WriteLine($"{<%= FULLWIDTH_LEFT_CURLY_BRACKET %>" = "{") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %>{" = "{") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %><%= FULLWIDTH_LEFT_CURLY_BRACKET %>" = "{") WriteLine(<%= FULLWIDTH_DOLLAR_SIGN %><%= FULLWIDTH_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %>" = """") End Sub End Module</file> </compilation>, expectedOutput:="True True True True True True True True True True True") End Sub <Fact> Public Sub NestedInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Write($"The date/time is {$"{#2014-12-18 09:00:00#:yyyy-MM-dd HH:mm:ss}"}.") End Sub End Module </file> </compilation>, expectedOutput:="The date/time is 2014-12-18 09:00:00.") End Sub <Fact> Public Sub StringToCharArrayConversion() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As Char() = $"{1} + {1} = {2}" Write(s.Length) End Sub End Module </file> </compilation>, expectedOutput:="9") End Sub <Fact> Public Sub UserDefinedConversions() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As C = "{1} + {1} = {2}" End Sub End Module Class C Shared Widening Operator CType(obj As String) As C Write("CType") Return New C() End Operator End Class </file> </compilation>, expectedOutput:="CType") End Sub <Fact> Public Sub TargetTyping() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{1} + {1} = {2}" Write(CObj(s).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 2") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub TargetTypingThroughArrayLiteralsAndLambdas() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M(Of IFormattable)({$"", Nothing}) N(Of IFormattable)(Function() If True Then Return $"" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T()) Write(obj(0).GetType().Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(f().GetType().Name) End Sub End Module </file> </compilation>, expectedOutput:="ConcreteFormattableStringConcreteFormattableString") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub TargetTypingExplicitConversions() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim ctf = CType($"{1} + {1} = {2}", IFormattable) Dim ctfs = CType($"{1} + {1} = {2}", FormattableString) Dim dcf = DirectCast($"{1} + {1} = {2}", IFormattable) Dim dcfs = DirectCast($"{1} + {1} = {2}", FormattableString) Dim tcf = TryCast($"{1} + {1} = {2}", IFormattable) Dim tcfs = TryCast($"{1} + {1} = {2}", FormattableString) Write(CObj(ctf).ToString()) Write(CObj(ctfs).ToString()) Write(CObj(dcf).ToString()) Write(CObj(dcfs).ToString()) Write(CObj(tcf).ToString()) Write(CObj(tcfs).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 2") End Sub <Fact> Public Sub TargetTypingThroughArrayLiteralsAndLambdasWithNarrowingConversionFromString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M(Of Integer)({$"1", Nothing}) N(Of Integer)(Function() If True Then Return $"1" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T()) Write(obj(0).GetType().Name) Write(obj(0)) End Sub Sub N(Of T)(f As Func(Of T)) Write(f().GetType().Name) Write(f()) End Sub End Module </file> </compilation>, expectedOutput:="Int321Int321") End Sub <Fact> Public Sub InterpolatedStringConversionIsWidening() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Option Strict On Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{1} + {1} = {2}" Write(CObj(s).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 2") End Sub <Fact> Public Sub ParenthesizationPreventsTargetTyping() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = ($"{1} + {1} = {2}") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC42322: Runtime errors might occur when converting 'String' to 'IFormattable'. Dim s As IFormattable = ($"{1} + {1} = {2}") ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub InvariantCulture() Dim previousCulture = Threading.Thread.CurrentThread.CurrentCulture Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Imports System.Threading Imports System.Globalization Imports System.FormattableString Module Program Sub Main() Dim previousCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE") Write($"{1.5}") Write(CObj(CType($"{1.5}", IFormattable)).ToString()) Write(CObj(CType($"{1.5}", FormattableString)).ToString()) Write(Invariant($"{1.5}")) Finally Thread.CurrentThread.CurrentCulture = previousCulture End Try End Sub End Module </file> </compilation>, expectedOutput:="1,51,51,51.5") Assert.Equal(previousCulture, Threading.Thread.CurrentThread.CurrentCulture) End Sub <Fact> Public Sub OverloadResolutionWithStringAndIFormattablePrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithStringAndFormattableStringPrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithIFormattableAndFormattableStringPrefersFormattableString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="FormattableString") End Sub <Fact> Public Sub OverloadResolutionWithStringIFormattableAndFormattableStringPrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithFuncOfStringAndFuncOfFormattableStringPrefersFuncOfString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M(Function() $"") End Sub Sub M(f As Func(Of String)) Write("String") End Sub Sub M(f As Func(Of FormattableString)) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub TypeInferredAsString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s = $"{1} + {1} = {2}" M(s) Dim arr1 = {$""} M(arr1) Dim arr2 = {$"", $""} M(arr2) M($"") End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="StringString[]String[]String") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(stringType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithNothingLiteralInferredAsString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M({$"", Nothing}) M(If(True, Nothing, $"")) N(Function() If True Then Return $"" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="String[]StringString") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(stringType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithIFormattableCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim iFormattableInstance As IFormattable = $"" M({$"", Nothing, iFormattableInstance}) M(If(True, iFormattableInstance, $"")) N(Function() If True Then Return $"" ElseIf True Then Return iFormattableInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="Object[]ObjectObject") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim objectType = compilation.GetSpecialType(SpecialType.System_Object) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(objectType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithFormattableStringCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" M({$"", Nothing, formattableStringInstance}) M(If(True, formattableStringInstance, $"")) N(Function() If True Then Return $"" ElseIf True Then Return formattableStringInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="Object[]ObjectObject") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim objectType = compilation.GetSpecialType(SpecialType.System_Object) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(objectType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithIFormattableAndFormattableStringCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" Dim iFormattableInstance As IFormattable = $"" M({$"", Nothing, formattableStringInstance, iFormattableInstance}) N(Function() If True Then Return $"" ElseIf True Then Return formattableStringInstance ElseIf True Then Return iFormattableInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="IFormattable[]IFormattable") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") Dim interpolatedStrings = root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).ToArray() Dim formattableStringType = compilation.GetTypeByMetadataName("System.FormattableString") Assert.True(sm.GetSymbolInfo(interpolatedStrings(0)).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(interpolatedStrings(0)) Assert.Equal(stringType, info.Type) Assert.Equal(formattableStringType, info.ConvertedType) For Each e In interpolatedStrings.Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub ERR_InterpolationAlignmentOutOfRange() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write($"This alignment is just small enough {New Object,32767}.") ' Short.MaxValue Write($"This alignment is too big {New Object,32768}.") ' Short.MaxValue + 1 Write($"This alignment is too small {New Object,-32768}.") ' -Short.MaxValue - 1 Write($"This alignment is just big enough {New Object,-32767}.") ' -Short.MaxValue Write($"This alignment is way too big {New Object,9223372036854775808}.") ' Long.MaxValue + 1 End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC37250: Alignment value is outside of the supported range. Write($"This alignment is too big {New Object,32768}.") ' Short.MaxValue + 1 ~~~~~ BC37250: Alignment value is outside of the supported range. Write($"This alignment is too small {New Object,-32768}.") ' -Short.MaxValue - 1 ~~~~~~ BC30036: Overflow. Write($"This alignment is way too big {New Object,9223372036854775808}.") ' Long.MaxValue + 1 ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Error_AmbiguousTypeArgumentInferenceWithIFormattable() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim iFormattableInstance As IFormattable = $"" M($"", iFormattableInstance) End Sub Sub M(Of T)(a As T, b As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC36651: Data type(s) of the type parameter(s) in method 'Public Sub M(Of T)(a As T, b As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. M($"", iFormattableInstance) ~ </expected>) End Sub <Fact> Public Sub Error_AmbiguousTypeArgumentInferenceWithFormattableString() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" M($"", formattableStringInstance) End Sub Sub M(Of T)(a As T, b As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub M(Of T)(a As T, b As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. M($"", formattableStringInstance) ~ </expected>) End Sub <Fact> Public Sub Error_InterpolationExpressionNotAValue() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write($"Expression {AddressOf Main} is not a value.") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Write($"Expression {AddressOf Main} is not a value.") ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub FlowAnalysis_Warning_InterpolatedVariableUsedBeforeBeingAssigned() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object Write($"{v}") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. Write($"{v}") ~ </expected>) End Sub <Fact> Public Sub FlowAnalysis_InterpolatedLocalConstNotConsideredUnused() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Const v As Object = Nothing Write($"{v}") End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) End Sub <Fact> Public Sub FlowAnalysis_AnalyzeDataFlowReportsCorrectResultsForVariablesUsedInInterpolations() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object = Nothing WriteLine($"{v}") WriteLine(v) End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim vSymbol = CType(sm.GetDeclaredSymbol(root.DescendantNodes().OfType(Of ModifiedIdentifierSyntax).Single()), ILocalSymbol) Dim writeLineCall = root.DescendantNodes().OfType(Of ExpressionStatementSyntax).First() Assert.Equal("WriteLine($""{v}"")", writeLineCall.ToString()) Dim analysis = sm.AnalyzeDataFlow(writeLineCall) Assert.True(analysis.Succeeded) Assert.DoesNotContain(vSymbol, analysis.AlwaysAssigned) Assert.DoesNotContain(vSymbol, analysis.Captured) Assert.Contains(vSymbol, analysis.DataFlowsIn) Assert.DoesNotContain(vSymbol, analysis.DataFlowsOut) Assert.Contains(vSymbol, analysis.ReadInside) Assert.Contains(vSymbol, analysis.ReadOutside) Assert.DoesNotContain(vSymbol, analysis.UnsafeAddressTaken) Assert.DoesNotContain(vSymbol, analysis.VariablesDeclared) Assert.DoesNotContain(vSymbol, analysis.WrittenInside) Assert.Contains(vSymbol, analysis.WrittenOutside) End Sub <Fact> Public Sub FlowAnalysis_AnalyzeDataFlowReportsCorrectResultsForVariablesCapturedInInterpolations() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object = Nothing WriteLine($"{(Function() v)()}") WriteLine(v) End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim vSymbol = CType(sm.GetDeclaredSymbol(root.DescendantNodes().OfType(Of ModifiedIdentifierSyntax).Single()), ILocalSymbol) Dim writeLineCall = root.DescendantNodes().OfType(Of ExpressionStatementSyntax).First() Assert.Equal("WriteLine($""{(Function() v)()}"")", writeLineCall.ToString()) Dim analysis = sm.AnalyzeDataFlow(writeLineCall) Assert.True(analysis.Succeeded) Assert.DoesNotContain(vSymbol, analysis.AlwaysAssigned) Assert.Contains(vSymbol, analysis.Captured) Assert.Contains(vSymbol, analysis.DataFlowsIn) Assert.DoesNotContain(vSymbol, analysis.DataFlowsOut) Assert.Contains(vSymbol, analysis.ReadInside) Assert.Contains(vSymbol, analysis.ReadOutside) Assert.DoesNotContain(vSymbol, analysis.UnsafeAddressTaken) Assert.DoesNotContain(vSymbol, analysis.VariablesDeclared) Assert.DoesNotContain(vSymbol, analysis.WrittenInside) Assert.Contains(vSymbol, analysis.WrittenOutside) End Sub <Fact> Public Sub Lowering_MissingFormattableStringDoesntProduceErrorIfFactoryMethodReturnsTypeConvertableToIFormattable() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As IFormattable Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write(CObj(CType($"{Nothing}.", IFormattable))) End Sub End Module </file> </compilation>, expectedOutput:="") End Sub <Fact> Public Sub Lowering_CallsMostOptimalStringFormatOverload() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Throw New NotImplementedException() End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, arg As Object) As FormattableString Console.Write("1 arg") Return Nothing End Function Public Function Create(formatString As String, arg1 As Object, arg2 as Object) As FormattableString Console.Write("2 arg") Return Nothing End Function Public Function Create(formatString As String, arg1 As Object, arg2 as Object, arg3 As Object) As FormattableString Console.Write("3 arg") Return Nothing End Function Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Console.Write("ParamArray") Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim empty As IFormattable = $"" Dim literal As IFormattable = $"Text" Dim one As IFormattable = $"One interpolation {Date.Now.Hour}" Dim two As IFormattable = $"Two interpolations {Date.Now.Hour}:{Date.Now.Minute}" Dim three As IFormattable = $"Three interpolations {Date.Now.Hour}:{Date.Now.Minute}:{Date.Now.Second}" Dim four As IFormattable = $"Four interpolations {Date.Now.Hour}:{Date.Now.Minute}:{Date.Now.Second}.{Date.Now.Millisecond}" End Sub End Module </file> </compilation>, expectedOutput:="ParamArrayParamArray1 arg2 arg3 argParamArray") End Sub <Fact> Public Sub Lowering_DoesNotCallFactoryMethodWithParamArrayInNormalForm() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Throw New NotImplementedException() End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Console.Write(If(args Is Nothing, "Null", args.Length)) Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim one As IFormattable = $"One interpolation {Nothing}" End Sub End Module </file> </compilation>, expectedOutput:="1") End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsMissing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write(CType($"{1}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{1}.", IFormattable)) ~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsSub() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Sub Create(formatString As String, ParamArray args As Object()) End Sub Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsNotAMethod() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public ReadOnly Property Create(formatString As String, ParamArray args As Object()) As FormattableString Get Return New ConcreteFormattableString(formatString, args) End Get End Property Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateMethodIsShadowedByField() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Class FormattableStringFactoryBase Public Shared Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return Nothing End Function End Class Public Class FormattableStringFactory Inherits FormattableStringFactoryBase Public Shadows Shared Create As Func(Of String, Object(), FormattableString) = Function(s, args) New ConcreteFormattableString(s, args) Protected NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Class End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsInAccessible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Private Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return New ConcreteFormattableString(formatString, args) End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30390: 'FormattableStringFactory.Private Function Create(formatString As String, ParamArray args As Object()) As FormattableString' is not accessible in this context because it is 'Private'. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateReturnIsNotConvertible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As Object() Return {formatString, args} End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30311: Value of type 'Object()' cannot be converted to 'IFormattable'. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_ArgArrayIsNotConvertible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Integer()) As FormattableString Return Nothing End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{New String() {}}" End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Dim s As IFormattable = $"{New String() {}}" ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'String()' cannot be converted to 'Integer'. Dim s As IFormattable = $"{New String() {}}" ~~~~~~~~~~~~~~~ </expected>) 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.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InterpolatedStringTests Inherits BasicTestBase Private ReadOnly _formattableStringSource As Xml.Linq.XElement = <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return New ConcreteFormattableString(formatString, args) End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <Fact> Public Sub SimpleInterpolation() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 8675309") End Sub <Fact> Public Sub InterpolationWithAlignment() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,12}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 8675309") End Sub <Fact> Public Sub InterpolationWithAlignmentWithNonDecimalBaseAndOrTypeSuffix() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,&amp;H1A} {1,1UL}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: " & "8675309".PadLeft(&H1A) & " 1") End Sub <Fact> Public Sub InterpolationWithFormat() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number:###-####}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 867-5309") End Sub <Fact> Public Sub InterpolationWithFormatAndAlignment() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim number = 8675309 Write($"Jenny: {number,12:###-####}") End Sub End Module </file> </compilation>, expectedOutput:="Jenny: 867-5309") End Sub <Fact> Public Sub TwoInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim Hello = "Goodbye", World = "No one" Write($"This is a ""{NameOf(Hello)}, {NameOf(World)}!"" program.") End Sub End Module </file> </compilation>, expectedOutput:="This is a ""Hello, World!"" program.") End Sub <Fact> Public Sub EscapeSequences() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Dim arr As Object() = {} Write($"Solution: {{ { If(arr.Length > 0, String.Join("", "", arr), "Ø") } }}") End Sub End Module </file> </compilation>, expectedOutput:="Solution: { Ø }") End Sub <Fact> Public Sub EscapeSequencesWitNoInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Write($"{{Ø}}") End Sub End Module </file> </compilation>, expectedOutput:="{Ø}") End Sub <Fact, WorkItem(1102783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1102783")> Public Sub SmartQuotes() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Sub Main() Dim arr = { $<%= LEFT_DOUBLE_QUOTATION_MARK %>1<%= RIGHT_DOUBLE_QUOTATION_MARK %>, $<%= RIGHT_DOUBLE_QUOTATION_MARK %>2<%= LEFT_DOUBLE_QUOTATION_MARK %>, $<%= LEFT_DOUBLE_QUOTATION_MARK %>3", $"4<%= LEFT_DOUBLE_QUOTATION_MARK %>, $"5<%= RIGHT_DOUBLE_QUOTATION_MARK %>, $<%= RIGHT_DOUBLE_QUOTATION_MARK %>6", $" <%= RIGHT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %> ", $<%= RIGHT_DOUBLE_QUOTATION_MARK %> {1:x<%= RIGHT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %>y} <%= LEFT_DOUBLE_QUOTATION_MARK %> } System.Console.WriteLine(String.Join("", arr)) End Sub End Module </file> </compilation>, expectedOutput:="123456 "" xy") End Sub <Fact, WorkItem(1102800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1102800")> Public Sub FullwidthDelimiters() ' Any combination of fullwidth and ASCII curly braces of the same direction is an escaping sequence for the corresponding ASCII curly brace. ' We insert that curly brace doubled and because this is the escaping sequence understood by String.Format, that will be replaced by a single brace. ' This is deliberate design and it aligns with existing rules for double quote escaping in strings. CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() WriteLine($"{0<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "0") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %>10<%= FULLWIDTH_COLON %>X}" = "A") WriteLine($"}}" = "}") WriteLine($"}<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "}") WriteLine($"<%= FULLWIDTH_RIGHT_CURLY_BRACKET %>}" = "}") WriteLine($"<%= FULLWIDTH_RIGHT_CURLY_BRACKET %><%= FULLWIDTH_RIGHT_CURLY_BRACKET %>" = "}") WriteLine($"{{" = "{") WriteLine($"{<%= FULLWIDTH_LEFT_CURLY_BRACKET %>" = "{") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %>{" = "{") WriteLine($"<%= FULLWIDTH_LEFT_CURLY_BRACKET %><%= FULLWIDTH_LEFT_CURLY_BRACKET %>" = "{") WriteLine(<%= FULLWIDTH_DOLLAR_SIGN %><%= FULLWIDTH_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %><%= LEFT_DOUBLE_QUOTATION_MARK %>" = """") End Sub End Module</file> </compilation>, expectedOutput:="True True True True True True True True True True True") End Sub <Fact> Public Sub NestedInterpolations() Dim verifier = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Console Module Program Sub Main() Write($"The date/time is {$"{#2014-12-18 09:00:00#:yyyy-MM-dd HH:mm:ss}"}.") End Sub End Module </file> </compilation>, expectedOutput:="The date/time is 2014-12-18 09:00:00.") End Sub <Fact> Public Sub StringToCharArrayConversion() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As Char() = $"{1} + {1} = {2}" Write(s.Length) End Sub End Module </file> </compilation>, expectedOutput:="9") End Sub <Fact> Public Sub UserDefinedConversions() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As C = "{1} + {1} = {2}" End Sub End Module Class C Shared Widening Operator CType(obj As String) As C Write("CType") Return New C() End Operator End Class </file> </compilation>, expectedOutput:="CType") End Sub <Fact> Public Sub TargetTyping() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{1} + {1} = {2}" Write(CObj(s).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 2") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub TargetTypingThroughArrayLiteralsAndLambdas() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M(Of IFormattable)({$"", Nothing}) N(Of IFormattable)(Function() If True Then Return $"" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T()) Write(obj(0).GetType().Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(f().GetType().Name) End Sub End Module </file> </compilation>, expectedOutput:="ConcreteFormattableStringConcreteFormattableString") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub TargetTypingExplicitConversions() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim ctf = CType($"{1} + {1} = {2}", IFormattable) Dim ctfs = CType($"{1} + {1} = {2}", FormattableString) Dim dcf = DirectCast($"{1} + {1} = {2}", IFormattable) Dim dcfs = DirectCast($"{1} + {1} = {2}", FormattableString) Dim tcf = TryCast($"{1} + {1} = {2}", IFormattable) Dim tcfs = TryCast($"{1} + {1} = {2}", FormattableString) Write(CObj(ctf).ToString()) Write(CObj(ctfs).ToString()) Write(CObj(dcf).ToString()) Write(CObj(dcfs).ToString()) Write(CObj(tcf).ToString()) Write(CObj(tcfs).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 21 + 1 = 2") End Sub <Fact> Public Sub TargetTypingThroughArrayLiteralsAndLambdasWithNarrowingConversionFromString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M(Of Integer)({$"1", Nothing}) N(Of Integer)(Function() If True Then Return $"1" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T()) Write(obj(0).GetType().Name) Write(obj(0)) End Sub Sub N(Of T)(f As Func(Of T)) Write(f().GetType().Name) Write(f()) End Sub End Module </file> </compilation>, expectedOutput:="Int321Int321") End Sub <Fact> Public Sub InterpolatedStringConversionIsWidening() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Option Strict On Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{1} + {1} = {2}" Write(CObj(s).ToString()) End Sub End Module </file> </compilation>, expectedOutput:="1 + 1 = 2") End Sub <Fact> Public Sub ParenthesizationPreventsTargetTyping() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = ($"{1} + {1} = {2}") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC42322: Runtime errors might occur when converting 'String' to 'IFormattable'. Dim s As IFormattable = ($"{1} + {1} = {2}") ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub InvariantCulture() Dim previousCulture = Threading.Thread.CurrentThread.CurrentCulture Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Imports System.Threading Imports System.Globalization Imports System.FormattableString Module Program Sub Main() Dim previousCulture = Thread.CurrentThread.CurrentCulture Try Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de-DE") Write($"{1.5}") Write(CObj(CType($"{1.5}", IFormattable)).ToString()) Write(CObj(CType($"{1.5}", FormattableString)).ToString()) Write(Invariant($"{1.5}")) Finally Thread.CurrentThread.CurrentCulture = previousCulture End Try End Sub End Module </file> </compilation>, expectedOutput:="1,51,51,51.5") Assert.Equal(previousCulture, Threading.Thread.CurrentThread.CurrentCulture) End Sub <Fact> Public Sub OverloadResolutionWithStringAndIFormattablePrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithStringAndFormattableStringPrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithIFormattableAndFormattableStringPrefersFormattableString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="FormattableString") End Sub <Fact> Public Sub OverloadResolutionWithStringIFormattableAndFormattableStringPrefersString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M($"") End Sub Sub M(s As String) Write("String") End Sub Sub M(s As IFormattable) Write("IFormattable") End Sub Sub M(s As FormattableString) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub OverloadResolutionWithFuncOfStringAndFuncOfFormattableStringPrefersFuncOfString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main(args As String()) M(Function() $"") End Sub Sub M(f As Func(Of String)) Write("String") End Sub Sub M(f As Func(Of FormattableString)) Write("FormattableString") End Sub End Module </file> </compilation>, expectedOutput:="String") End Sub <Fact> Public Sub TypeInferredAsString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s = $"{1} + {1} = {2}" M(s) Dim arr1 = {$""} M(arr1) Dim arr2 = {$"", $""} M(arr2) M($"") End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="StringString[]String[]String") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(stringType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithNothingLiteralInferredAsString() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() M({$"", Nothing}) M(If(True, Nothing, $"")) N(Function() If True Then Return $"" Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="String[]StringString") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(stringType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithIFormattableCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim iFormattableInstance As IFormattable = $"" M({$"", Nothing, iFormattableInstance}) M(If(True, iFormattableInstance, $"")) N(Function() If True Then Return $"" ElseIf True Then Return iFormattableInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="Object[]ObjectObject") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim objectType = compilation.GetSpecialType(SpecialType.System_Object) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(objectType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithFormattableStringCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" M({$"", Nothing, formattableStringInstance}) M(If(True, formattableStringInstance, $"")) N(Function() If True Then Return $"" ElseIf True Then Return formattableStringInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="Object[]ObjectObject") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim objectType = compilation.GetSpecialType(SpecialType.System_Object) For Each e In root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(objectType, info.ConvertedType) Next End Sub <Fact> Public Sub DominantTypeWithIFormattableAndFormattableStringCannotBeInferred() Dim verifier = CompileAndVerify( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" Dim iFormattableInstance As IFormattable = $"" M({$"", Nothing, formattableStringInstance, iFormattableInstance}) N(Function() If True Then Return $"" ElseIf True Then Return formattableStringInstance ElseIf True Then Return iFormattableInstance Else Return Nothing End If End Function) End Sub Sub M(Of T)(obj As T) Write(GetType(T).Name) End Sub Sub N(Of T)(f As Func(Of T)) Write(GetType(T).Name) End Sub End Module </file> </compilation>, expectedOutput:="IFormattable[]IFormattable") Dim compilation = verifier.Compilation Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim stringType = compilation.GetSpecialType(SpecialType.System_String) Dim iFormattableType = compilation.GetTypeByMetadataName("System.IFormattable") Dim interpolatedStrings = root.DescendantNodes().OfType(Of InterpolatedStringExpressionSyntax).ToArray() Dim formattableStringType = compilation.GetTypeByMetadataName("System.FormattableString") Assert.True(sm.GetSymbolInfo(interpolatedStrings(0)).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") Dim info = sm.GetTypeInfo(interpolatedStrings(0)) Assert.Equal(stringType, info.Type) Assert.Equal(formattableStringType, info.ConvertedType) For Each e In interpolatedStrings.Skip(1) Assert.True(sm.GetSymbolInfo(e).IsEmpty, "Interpolated String expressions shouldn't bind to symbols.") info = sm.GetTypeInfo(e) Assert.Equal(stringType, info.Type) Assert.Equal(iFormattableType, info.ConvertedType) Next End Sub <Fact> Public Sub ERR_InterpolationAlignmentOutOfRange() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write($"This alignment is just small enough {New Object,32767}.") ' Short.MaxValue Write($"This alignment is too big {New Object,32768}.") ' Short.MaxValue + 1 Write($"This alignment is too small {New Object,-32768}.") ' -Short.MaxValue - 1 Write($"This alignment is just big enough {New Object,-32767}.") ' -Short.MaxValue Write($"This alignment is way too big {New Object,9223372036854775808}.") ' Long.MaxValue + 1 End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC37250: Alignment value is outside of the supported range. Write($"This alignment is too big {New Object,32768}.") ' Short.MaxValue + 1 ~~~~~ BC37250: Alignment value is outside of the supported range. Write($"This alignment is too small {New Object,-32768}.") ' -Short.MaxValue - 1 ~~~~~~ BC30036: Overflow. Write($"This alignment is way too big {New Object,9223372036854775808}.") ' Long.MaxValue + 1 ~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Error_AmbiguousTypeArgumentInferenceWithIFormattable() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim iFormattableInstance As IFormattable = $"" M($"", iFormattableInstance) End Sub Sub M(Of T)(a As T, b As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC36651: Data type(s) of the type parameter(s) in method 'Public Sub M(Of T)(a As T, b As T)' cannot be inferred from these arguments because more than one type is possible. Specifying the data type(s) explicitly might correct this error. M($"", iFormattableInstance) ~ </expected>) End Sub <Fact> Public Sub Error_AmbiguousTypeArgumentInferenceWithFormattableString() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim formattableStringInstance As FormattableString = $"" M($"", formattableStringInstance) End Sub Sub M(Of T)(a As T, b As T) Write(GetType(T).Name) End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC36657: Data type(s) of the type parameter(s) in method 'Public Sub M(Of T)(a As T, b As T)' cannot be inferred from these arguments because they do not convert to the same type. Specifying the data type(s) explicitly might correct this error. M($"", formattableStringInstance) ~ </expected>) End Sub <Fact> Public Sub Error_InterpolationExpressionNotAValue() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write($"Expression {AddressOf Main} is not a value.") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Write($"Expression {AddressOf Main} is not a value.") ~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub FlowAnalysis_Warning_InterpolatedVariableUsedBeforeBeingAssigned() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object Write($"{v}") End Sub End Module </file> </compilation>) AssertTheseCompileDiagnostics(compilation, <expected> BC42104: Variable 'v' is used before it has been assigned a value. A null reference exception could result at runtime. Write($"{v}") ~ </expected>) End Sub <Fact> Public Sub FlowAnalysis_InterpolatedLocalConstNotConsideredUnused() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Const v As Object = Nothing Write($"{v}") End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) End Sub <Fact> Public Sub FlowAnalysis_AnalyzeDataFlowReportsCorrectResultsForVariablesUsedInInterpolations() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object = Nothing WriteLine($"{v}") WriteLine(v) End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim vSymbol = CType(sm.GetDeclaredSymbol(root.DescendantNodes().OfType(Of ModifiedIdentifierSyntax).Single()), ILocalSymbol) Dim writeLineCall = root.DescendantNodes().OfType(Of ExpressionStatementSyntax).First() Assert.Equal("WriteLine($""{v}"")", writeLineCall.ToString()) Dim analysis = sm.AnalyzeDataFlow(writeLineCall) Assert.True(analysis.Succeeded) Assert.DoesNotContain(vSymbol, analysis.AlwaysAssigned) Assert.DoesNotContain(vSymbol, analysis.Captured) Assert.Contains(vSymbol, analysis.DataFlowsIn) Assert.DoesNotContain(vSymbol, analysis.DataFlowsOut) Assert.Contains(vSymbol, analysis.ReadInside) Assert.Contains(vSymbol, analysis.ReadOutside) Assert.DoesNotContain(vSymbol, analysis.UnsafeAddressTaken) Assert.DoesNotContain(vSymbol, analysis.VariablesDeclared) Assert.DoesNotContain(vSymbol, analysis.WrittenInside) Assert.Contains(vSymbol, analysis.WrittenOutside) End Sub <Fact> Public Sub FlowAnalysis_AnalyzeDataFlowReportsCorrectResultsForVariablesCapturedInInterpolations() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <%= _formattableStringSource %> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim v As Object = Nothing WriteLine($"{(Function() v)()}") WriteLine(v) End Sub End Module </file> </compilation>) AssertNoDiagnostics(compilation) Dim mainTree = Aggregate t In compilation.SyntaxTrees Where t.FilePath = "a.vb" Into [Single]() Dim root = mainTree.GetRoot() Dim sm = compilation.GetSemanticModel(mainTree) Dim vSymbol = CType(sm.GetDeclaredSymbol(root.DescendantNodes().OfType(Of ModifiedIdentifierSyntax).Single()), ILocalSymbol) Dim writeLineCall = root.DescendantNodes().OfType(Of ExpressionStatementSyntax).First() Assert.Equal("WriteLine($""{(Function() v)()}"")", writeLineCall.ToString()) Dim analysis = sm.AnalyzeDataFlow(writeLineCall) Assert.True(analysis.Succeeded) Assert.DoesNotContain(vSymbol, analysis.AlwaysAssigned) Assert.Contains(vSymbol, analysis.Captured) Assert.Contains(vSymbol, analysis.DataFlowsIn) Assert.DoesNotContain(vSymbol, analysis.DataFlowsOut) Assert.Contains(vSymbol, analysis.ReadInside) Assert.Contains(vSymbol, analysis.ReadOutside) Assert.DoesNotContain(vSymbol, analysis.UnsafeAddressTaken) Assert.DoesNotContain(vSymbol, analysis.VariablesDeclared) Assert.DoesNotContain(vSymbol, analysis.WrittenInside) Assert.Contains(vSymbol, analysis.WrittenOutside) End Sub <Fact> Public Sub Lowering_MissingFormattableStringDoesntProduceErrorIfFactoryMethodReturnsTypeConvertableToIFormattable() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As IFormattable Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write(CObj(CType($"{Nothing}.", IFormattable))) End Sub End Module </file> </compilation>, expectedOutput:="") End Sub <Fact> Public Sub Lowering_CallsMostOptimalStringFormatOverload() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Throw New NotImplementedException() End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, arg As Object) As FormattableString Console.Write("1 arg") Return Nothing End Function Public Function Create(formatString As String, arg1 As Object, arg2 as Object) As FormattableString Console.Write("2 arg") Return Nothing End Function Public Function Create(formatString As String, arg1 As Object, arg2 as Object, arg3 As Object) As FormattableString Console.Write("3 arg") Return Nothing End Function Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Console.Write("ParamArray") Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim empty As IFormattable = $"" Dim literal As IFormattable = $"Text" Dim one As IFormattable = $"One interpolation {Date.Now.Hour}" Dim two As IFormattable = $"Two interpolations {Date.Now.Hour}:{Date.Now.Minute}" Dim three As IFormattable = $"Three interpolations {Date.Now.Hour}:{Date.Now.Minute}:{Date.Now.Second}" Dim four As IFormattable = $"Four interpolations {Date.Now.Hour}:{Date.Now.Minute}:{Date.Now.Second}.{Date.Now.Millisecond}" End Sub End Module </file> </compilation>, expectedOutput:="ParamArrayParamArray1 arg2 arg3 argParamArray") End Sub <Fact> Public Sub Lowering_DoesNotCallFactoryMethodWithParamArrayInNormalForm() Dim verifier = CompileAndVerify( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Throw New NotImplementedException() End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As FormattableString Console.Write(If(args Is Nothing, "Null", args.Length)) Return Nothing End Function End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim one As IFormattable = $"One interpolation {Nothing}" End Sub End Module </file> </compilation>, expectedOutput:="1") End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsMissing() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Write(CType($"{1}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{1}.", IFormattable)) ~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsSub() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Sub Create(formatString As String, ParamArray args As Object()) End Sub Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsNotAMethod() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public ReadOnly Property Create(formatString As String, ParamArray args As Object()) As FormattableString Get Return New ConcreteFormattableString(formatString, args) End Get End Property Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateMethodIsShadowedByField() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Class FormattableStringFactoryBase Public Shared Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return Nothing End Function End Class Public Class FormattableStringFactory Inherits FormattableStringFactoryBase Public Shadows Shared Create As Func(Of String, Object(), FormattableString) = Function(s, args) New ConcreteFormattableString(s, args) Protected NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Class End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateIsInAccessible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Private Function Create(formatString As String, ParamArray args As Object()) As FormattableString Return New ConcreteFormattableString(formatString, args) End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30390: 'FormattableStringFactory.Private Function Create(formatString As String, ParamArray args As Object()) As FormattableString' is not accessible in this context because it is 'Private'. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_CreateReturnIsNotConvertible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Object()) As Object() Return {formatString, args} End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim obj As Object = Nothing Write(CType($"{obj}.", IFormattable)) End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC30311: Value of type 'Object()' cannot be converted to 'IFormattable'. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Write(CType($"{obj}.", IFormattable)) ~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Lowering_ERR_InterpolatedStringFactoryError_ArgArrayIsNotConvertible() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences( <compilation> <file name="FormattableString.vb"> Namespace System Public MustInherit Class FormattableString Implements IFormattable Public NotOverridable Overrides Function ToString() As String Return ToString(Globalization.CultureInfo.CurrentCulture) End Function Public MustOverride Overloads Function ToString(formatProvider As IFormatProvider) As String Public Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString Return ToString(formatProvider) End Function Public Shared Function Invariant(formattable As FormattableString) As String Return formattable.ToString(Globalization.CultureInfo.InvariantCulture) End Function End Class End Namespace Namespace System.Runtime.CompilerServices Public Module FormattableStringFactory Public Function Create(formatString As String, ParamArray args As Integer()) As FormattableString Return Nothing End Function Private NotInheritable Class ConcreteFormattableString Inherits FormattableString Private ReadOnly FormatString As String Private ReadOnly Arguments As Object() Public Sub New(formatString As String, arguments As Object()) Me.FormatString = formatString Me.Arguments = arguments End Sub Public Overrides Function ToString(provider As IFormatProvider) As String Return String.Format(provider, FormatString, Arguments) End Function End Class End Module End Namespace </file> <file name="a.vb"> Imports System Imports System.Console Module Program Sub Main() Dim s As IFormattable = $"{New String() {}}" End Sub End Module </file> </compilation>) AssertTheseEmitDiagnostics(compilation, <expected> BC37251: There were one or more errors emitting a call to FormattableStringFactory.Create. Method or its return type may be missing or malformed. Dim s As IFormattable = $"{New String() {}}" ~~~~~~~~~~~~~~~~~~~~ BC30311: Value of type 'String()' cannot be converted to 'Integer'. Dim s As IFormattable = $"{New String() {}}" ~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/VisualBasic/Hosting/ObjectFormatter/VisualBasicObjectFormatter.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.Scripting.Hosting Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting Public NotInheritable Class VisualBasicObjectFormatter Inherits ObjectFormatter Public Shared ReadOnly Property Instance As New VisualBasicObjectFormatter() Private Shared ReadOnly s_impl As ObjectFormatter = New VisualBasicObjectFormatterImpl() Private Sub New() End Sub Public Overrides Function FormatObject(obj As Object, options As PrintOptions) As String Return s_impl.FormatObject(obj, options) End Function Public Overrides Function FormatException(e As Exception) As String Return s_impl.FormatException(e) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Scripting.Hosting Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting Public NotInheritable Class VisualBasicObjectFormatter Inherits ObjectFormatter Public Shared ReadOnly Property Instance As New VisualBasicObjectFormatter() Private Shared ReadOnly s_impl As ObjectFormatter = New VisualBasicObjectFormatterImpl() Private Sub New() End Sub Public Overrides Function FormatObject(obj As Object, options As PrintOptions) As String Return s_impl.FormatObject(obj, options) End Function Public Overrides Function FormatException(e As Exception) As String Return s_impl.FormatException(e) End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/FieldReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class FieldReferenceFinder : AbstractCallFinder { public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName { get { return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName); } } protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return callers.Where(c => c.IsDirect); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders { internal class FieldReferenceFinder : AbstractCallFinder { public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider) : base(symbol, projectId, asyncListener, provider) { } public override string DisplayName { get { return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName); } } protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken) { var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false); return callers.Where(c => c.IsDirect); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Classification/SyntacticClassifierTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Classification { public partial class SyntacticClassifierTests : AbstractCSharpClassifierTests { protected override async Task<ImmutableArray<ClassifiedSpan>> GetClassificationSpansAsync(string code, TextSpan span, ParseOptions options, TestHost testHost) { using var workspace = CreateWorkspace(code, options, testHost); var document = workspace.CurrentSolution.Projects.First().Documents.First(); return await GetSyntacticClassificationsAsync(document, span); } [Theory] [CombinatorialData] public async Task VarAtTypeMemberLevel(TestHost testHost) { await TestAsync( @"class C { var goo }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("var"), Field("goo"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNamespace(TestHost testHost) { await TestAsync( @"namespace N { }", testHost, Keyword("namespace"), Namespace("N"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestFileScopedNamespace(TestHost testHost) { await TestAsync( @"namespace N; ", testHost, Keyword("namespace"), Namespace("N"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsLocalVariableType(TestHost testHost) { await TestInMethodAsync("var goo = 42", testHost, Keyword("var"), Local("goo"), Operators.Equals, Number("42")); } [Theory] [CombinatorialData] public async Task VarOptimisticallyColored(TestHost testHost) { await TestInMethodAsync("var", testHost, Keyword("var")); } [Theory] [CombinatorialData] public async Task VarNotColoredInClass(TestHost testHost) { await TestInClassAsync("var", testHost, Identifier("var")); } [Theory] [CombinatorialData] public async Task VarInsideLocalAndExpressions(TestHost testHost) { await TestInMethodAsync( @"var var = (var)var as var;", testHost, Keyword("var"), Local("var"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("var"), Keyword("as"), Identifier("var"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task VarAsMethodParameter(TestHost testHost) { await TestAsync( @"class C { void M(var v) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("v"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldYield(TestHost testHost) { await TestAsync( @"using System.Collections.Generic; class yield { IEnumerable<yield> M() { yield yield = new yield(); yield return yield; } }", testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon, Keyword("class"), Class("yield"), Punctuation.OpenCurly, Identifier("IEnumerable"), Punctuation.OpenAngle, Identifier("yield"), Punctuation.CloseAngle, Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("yield"), Local("yield"), Operators.Equals, Keyword("new"), Identifier("yield"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("return"), Identifier("yield"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task YieldReturn(TestHost testHost) { await TestInMethodAsync("yield return 42", testHost, ControlKeyword("yield"), ControlKeyword("return"), Number("42")); } [Theory] [CombinatorialData] public async Task YieldFixed(TestHost testHost) { await TestInMethodAsync( @"yield return this.items[0]; yield break; fixed (int* i = 0) { }", testHost, ControlKeyword("yield"), ControlKeyword("return"), Keyword("this"), Operators.Dot, Identifier("items"), Punctuation.OpenBracket, Number("0"), Punctuation.CloseBracket, Punctuation.Semicolon, ControlKeyword("yield"), ControlKeyword("break"), Punctuation.Semicolon, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("i"), Operators.Equals, Number("0"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task PartialClass(TestHost testHost) { await TestAsync("public partial class Goo", testHost, Keyword("public"), Keyword("partial"), Keyword("class"), Class("Goo")); } [Theory] [CombinatorialData] public async Task PartialMethod(TestHost testHost) { await TestInClassAsync( @"public partial void M() { }", testHost, Keyword("public"), Keyword("partial"), Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } /// <summary> /// Partial is only valid in a type declaration /// </summary> [Theory] [CombinatorialData] [WorkItem(536313, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536313")] public async Task PartialAsLocalVariableType(TestHost testHost) { await TestInMethodAsync( @"partial p1 = 42;", testHost, Identifier("partial"), Local("p1"), Operators.Equals, Number("42"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task PartialClassStructInterface(TestHost testHost) { await TestAsync( @"partial class T1 { } partial struct T2 { } partial interface T3 { }", testHost, Keyword("partial"), Keyword("class"), Class("T1"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("struct"), Struct("T2"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("interface"), Interface("T3"), Punctuation.OpenCurly, Punctuation.CloseCurly); } private static readonly string[] s_contextualKeywordsOnlyValidInMethods = new string[] { "where", "from", "group", "join", "select", "into", "let", "by", "orderby", "on", "equals", "ascending", "descending" }; /// <summary> /// Check for items only valid within a method declaration /// </summary> [Theory] [CombinatorialData] public async Task ContextualKeywordsOnlyValidInMethods(TestHost testHost) { foreach (var kw in s_contextualKeywordsOnlyValidInMethods) { await TestInNamespaceAsync(kw + " goo", testHost, Identifier(kw), Field("goo")); } } [Theory] [CombinatorialData] public async Task VerbatimStringLiterals1(TestHost testHost) { await TestInMethodAsync(@"@""goo""", testHost, Verbatim(@"@""goo""")); } /// <summary> /// Should show up as soon as we get the @\" typed out /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiterals2(TestHost testHost) { await TestAsync(@"@""", testHost, Verbatim(@"@""")); } /// <summary> /// Parser does not currently support strings of this type /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral3(TestHost testHost) { await TestAsync(@"goo @""", testHost, Identifier("goo"), Verbatim(@"@""")); } /// <summary> /// Uncompleted ones should span new lines /// </summary> [Theory] [CombinatorialData] public async Task VerbatimStringLiteral4(TestHost testHost) { var code = @" @"" goo bar "; await TestAsync(code, testHost, Verbatim(@"@"" goo bar ")); } [Theory] [CombinatorialData] public async Task VerbatimStringLiteral5(TestHost testHost) { var code = @" @"" goo bar and on a new line "" more stuff"; await TestInMethodAsync(code, testHost, Verbatim(@"@"" goo bar and on a new line """), Identifier("more"), Local("stuff")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VerbatimStringLiteral6(bool script, TestHost testHost) { var code = @"string s = @""""""/*"";"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("string"), script ? Field("s") : Local("s"), Operators.Equals, Verbatim(@"@""""""/*"""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task StringLiteral1(TestHost testHost) { await TestAsync(@"""goo""", testHost, String(@"""goo""")); } [Theory] [CombinatorialData] public async Task StringLiteral2(TestHost testHost) { await TestAsync(@"""""", testHost, String(@"""""")); } [Theory] [CombinatorialData] public async Task CharacterLiteral1(TestHost testHost) { var code = @"'f'"; await TestInMethodAsync(code, testHost, String("'f'")); } [Theory] [CombinatorialData] public async Task LinqFrom1(TestHost testHost) { var code = @"from it in goo"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo")); } [Theory] [CombinatorialData] public async Task LinqFrom2(TestHost testHost) { var code = @"from it in goo.Bar()"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Operators.Dot, Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task LinqFrom3(TestHost testHost) { // query expression are not statement expressions, but the parser parses them anyways to give better errors var code = @"from it in "; await TestInMethodAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqFrom4(TestHost testHost) { var code = @"from it in "; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in")); } [Theory] [CombinatorialData] public async Task LinqWhere1(TestHost testHost) { var code = "from it in goo where it > 42"; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, Number("42")); } [Theory] [CombinatorialData] public async Task LinqWhere2(TestHost testHost) { var code = @"from it in goo where it > ""bar"""; await TestInExpressionAsync(code, testHost, Keyword("from"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("where"), Identifier("it"), Operators.GreaterThan, String(@"""bar""")); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task VarContextualKeywordAtNamespaceLevel(bool script, TestHost testHost) { var code = @"var goo = 2;"; var parseOptions = script ? Options.Script : null; await TestAsync(code, code, testHost, parseOptions, script ? Identifier("var") : Keyword("var"), script ? Field("goo") : Local("goo"), Operators.Equals, Number("2"), Punctuation.Semicolon); } [Theory] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] [CombinatorialData] public async Task LinqKeywordsAtNamespaceLevel(bool script, TestHost testHost) { // the contextual keywords are actual keywords since we parse top level field declaration and only give a semantic error var code = @"object goo = from goo in goo join goo in goo on goo equals goo group goo by goo into goo let goo = goo where goo orderby goo ascending, goo descending select goo;"; var parseOptions = script ? Options.Script : null; await TestAsync( code, code, testHost, parseOptions, Keyword("object"), script ? Field("goo") : Local("goo"), Operators.Equals, Keyword("from"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("join"), Identifier("goo"), Keyword("in"), Identifier("goo"), Keyword("on"), Identifier("goo"), Keyword("equals"), Identifier("goo"), Keyword("group"), Identifier("goo"), Keyword("by"), Identifier("goo"), Keyword("into"), Identifier("goo"), Keyword("let"), Identifier("goo"), Operators.Equals, Identifier("goo"), Keyword("where"), Identifier("goo"), Keyword("orderby"), Identifier("goo"), Keyword("ascending"), Punctuation.Comma, Identifier("goo"), Keyword("descending"), Keyword("select"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ContextualKeywordsAsFieldName(TestHost testHost) { await TestAsync( @"class C { int yield, get, set, value, add, remove, global, partial, where, alias; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("yield"), Punctuation.Comma, Field("get"), Punctuation.Comma, Field("set"), Punctuation.Comma, Field("value"), Punctuation.Comma, Field("add"), Punctuation.Comma, Field("remove"), Punctuation.Comma, Field("global"), Punctuation.Comma, Field("partial"), Punctuation.Comma, Field("where"), Punctuation.Comma, Field("alias"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInFieldInitializer(TestHost testHost) { await TestAsync( @"class C { int a = from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("a"), Operators.Equals, Keyword("from"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("join"), Identifier("a"), Keyword("in"), Identifier("a"), Keyword("on"), Identifier("a"), Keyword("equals"), Identifier("a"), Keyword("group"), Identifier("a"), Keyword("by"), Identifier("a"), Keyword("into"), Identifier("a"), Keyword("let"), Identifier("a"), Operators.Equals, Identifier("a"), Keyword("where"), Identifier("a"), Keyword("orderby"), Identifier("a"), Keyword("ascending"), Punctuation.Comma, Identifier("a"), Keyword("descending"), Keyword("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsTypeName(TestHost testHost) { await TestAsync( @"class var { } struct from { } interface join { } enum on { } delegate equals { } class group { } class by { } class into { } class let { } class where { } class orderby { } class ascending { } class descending { } class select { }", testHost, Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("struct"), Struct("from"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("interface"), Interface("join"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("enum"), Enum("on"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Identifier("equals"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("group"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("by"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("into"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("let"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("where"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("orderby"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("ascending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("descending"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("select"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsMethodParameters(TestHost testHost) { await TestAsync( @"class C { orderby M(var goo, from goo, join goo, on goo, equals goo, group goo, by goo, into goo, let goo, where goo, orderby goo, ascending goo, descending goo, select goo) { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Identifier("orderby"), Method("M"), Punctuation.OpenParen, Identifier("var"), Parameter("goo"), Punctuation.Comma, Identifier("from"), Parameter("goo"), Punctuation.Comma, Identifier("join"), Parameter("goo"), Punctuation.Comma, Identifier("on"), Parameter("goo"), Punctuation.Comma, Identifier("equals"), Parameter("goo"), Punctuation.Comma, Identifier("group"), Parameter("goo"), Punctuation.Comma, Identifier("by"), Parameter("goo"), Punctuation.Comma, Identifier("into"), Parameter("goo"), Punctuation.Comma, Identifier("let"), Parameter("goo"), Punctuation.Comma, Identifier("where"), Parameter("goo"), Punctuation.Comma, Identifier("orderby"), Parameter("goo"), Punctuation.Comma, Identifier("ascending"), Parameter("goo"), Punctuation.Comma, Identifier("descending"), Parameter("goo"), Punctuation.Comma, Identifier("select"), Parameter("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsInLocalVariableDeclarations(TestHost testHost) { await TestAsync( @"class C { void M() { var goo = (var)goo as var; from goo = (from)goo as from; join goo = (join)goo as join; on goo = (on)goo as on; equals goo = (equals)goo as equals; group goo = (group)goo as group; by goo = (by)goo as by; into goo = (into)goo as into; orderby goo = (orderby)goo as orderby; ascending goo = (ascending)goo as ascending; descending goo = (descending)goo as descending; select goo = (select)goo as select; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("var"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("var"), Punctuation.Semicolon, Identifier("from"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("from"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("from"), Punctuation.Semicolon, Identifier("join"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("join"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("join"), Punctuation.Semicolon, Identifier("on"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("on"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("on"), Punctuation.Semicolon, Identifier("equals"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("equals"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("equals"), Punctuation.Semicolon, Identifier("group"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("group"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("group"), Punctuation.Semicolon, Identifier("by"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("by"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("by"), Punctuation.Semicolon, Identifier("into"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("into"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("into"), Punctuation.Semicolon, Identifier("orderby"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("orderby"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("orderby"), Punctuation.Semicolon, Identifier("ascending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("ascending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("ascending"), Punctuation.Semicolon, Identifier("descending"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("descending"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("descending"), Punctuation.Semicolon, Identifier("select"), Local("goo"), Operators.Equals, Punctuation.OpenParen, Identifier("select"), Punctuation.CloseParen, Identifier("goo"), Keyword("as"), Identifier("select"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAsFieldNames(TestHost testHost) { await TestAsync( @"class C { int var, from, join, on, into, equals, let, orderby, ascending, descending, select, group, by, partial; }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Field("var"), Punctuation.Comma, Field("from"), Punctuation.Comma, Field("join"), Punctuation.Comma, Field("on"), Punctuation.Comma, Field("into"), Punctuation.Comma, Field("equals"), Punctuation.Comma, Field("let"), Punctuation.Comma, Field("orderby"), Punctuation.Comma, Field("ascending"), Punctuation.Comma, Field("descending"), Punctuation.Comma, Field("select"), Punctuation.Comma, Field("group"), Punctuation.Comma, Field("by"), Punctuation.Comma, Field("partial"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task LinqKeywordsAtFieldLevelInvalid(TestHost testHost) { await TestAsync( @"class C { string Property { from a in a join a in a on a equals a group a by a into a let a = a where a orderby a ascending, a descending select a; } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("string"), Property("Property"), Punctuation.OpenCurly, Identifier("from"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("join"), Identifier("a"), Keyword("in"), Identifier("a"), Identifier("on"), Identifier("a"), Identifier("equals"), Identifier("a"), Identifier("group"), Identifier("a"), Identifier("by"), Identifier("a"), Identifier("into"), Identifier("a"), Identifier("let"), Identifier("a"), Operators.Equals, Identifier("a"), Identifier("where"), Identifier("a"), Identifier("orderby"), Identifier("a"), Identifier("ascending"), Punctuation.Comma, Identifier("a"), Identifier("descending"), Identifier("select"), Identifier("a"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentSingle(TestHost testHost) { var code = "// goo"; await TestAsync(code, testHost, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsTrailingTrivia1(TestHost testHost) { var code = "class Bar { // goo"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo")); } [Theory] [CombinatorialData] public async Task CommentAsLeadingTrivia1(TestHost testHost) { var code = @" class Bar { // goo void Method1() { } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Comment("// goo"), Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { Comment("#!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task ShebangAsFirstCommentInNonScript(TestHost testHost) { var code = @"#!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Regular, expected); } [Theory] [CombinatorialData] public async Task ShebangNotAsFirstCommentInScript(TestHost testHost) { var code = @" #!/usr/bin/env scriptcs System.Console.WriteLine();"; var expected = new[] { PPKeyword("#"), PPText("!/usr/bin/env scriptcs"), Identifier("System"), Operators.Dot, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon }; await TestAsync(code, code, testHost, Options.Script, expected); } [Theory] [CombinatorialData] public async Task CommentAsMethodBodyContent(TestHost testHost) { var code = @" class Bar { void Method1() { // goo } }"; await TestAsync(code, testHost, Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Keyword("void"), Method("Method1"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Comment("// goo"), Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CommentMix1(TestHost testHost) { await TestAsync( @"// comment1 /* class cl { } //comment2 */", testHost, Comment("// comment1 /*"), Keyword("class"), Class("cl"), Punctuation.OpenCurly, Punctuation.CloseCurly, Comment("//comment2 */")); } [Theory] [CombinatorialData] public async Task CommentMix2(TestHost testHost) { await TestInMethodAsync( @"/**/int /**/i = 0;", testHost, Comment("/**/"), Keyword("int"), Comment("/**/"), Local("i"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClass(TestHost testHost) { var code = @" /// <summary>something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithIndent(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EntityReference(TestHost testHost) { var code = @" /// <summary>&#65;</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCloseTag(TestHost testHost) { var code = @" /// <summary>something</ /// summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("///"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(531155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531155")] [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaInsideCRef(TestHost testHost) { var code = @" /// <see cref=""System. /// Int32""/> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("see"), XmlDoc.AttributeName("cref"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes("\""), Identifier("System"), Operators.Dot, XmlDoc.Delimiter("///"), Identifier("Int32"), XmlDoc.AttributeQuotes("\""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocCommentOnClassWithExteriorTrivia(TestHost testHost) { var code = @" /// <summary> /// something /// </summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text(" something"), XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExteriorTriviaNoText(TestHost testHost) { var code = @"///<summary> ///something ///</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Text("something"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_EmptyElement(TestHost testHost) { var code = @" /// <summary /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_Attribute(TestHost testHost) { var code = @" /// <summary attribute=""value"">something</summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_AttributeInEmptyElement(TestHost testHost) { var code = @" /// <summary attribute=""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ExtraSpaces(TestHost testHost) { var code = @" /// < summary attribute = ""value"" /> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.AttributeName("attribute"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(@""""), XmlDoc.AttributeValue(@"value"), XmlDoc.AttributeQuotes(@""""), XmlDoc.Delimiter("/>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlComment(TestHost testHost) { var code = @" ///<!--comment--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentWithExteriorTrivia(TestHost testHost) { var code = @" ///<!--first ///second--> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first"), XmlDoc.Delimiter("///"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_XmlCommentInElement(TestHost testHost) { var code = @" ///<summary><!--comment--></summary> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("comment"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(31410, "https://github.com/dotnet/roslyn/pull/31410")] public async Task XmlDocComment_MalformedXmlDocComment(TestHost testHost) { var code = @" ///<summary> ///<a: b, c />. ///</summary> class C { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<"), XmlDoc.Name("a"), XmlDoc.Name(":"), XmlDoc.Name("b"), XmlDoc.Text(","), XmlDoc.Text("c"), XmlDoc.Delimiter("/>"), XmlDoc.Text("."), XmlDoc.Delimiter("///"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task MultilineXmlDocComment_ExteriorTrivia(TestHost testHost) { var code = @"/**<summary> *comment *</summary>*/ class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("/**"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*"), XmlDoc.Text("comment"), XmlDoc.Delimiter("*"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("*/"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_CDataWithExteriorTrivia(TestHost testHost) { var code = @" ///<![CDATA[first ///second]]> class Bar { }"; await TestAsync(code, testHost, XmlDoc.Delimiter("///"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first"), XmlDoc.Delimiter("///"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), Keyword("class"), Class("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task XmlDocComment_ProcessingDirective(TestHost testHost) { await TestAsync( @"/// <summary><?goo /// ?></summary> public class Program { static void Main() { } }", testHost, XmlDoc.Delimiter("///"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.Delimiter("///"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("?>"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("public"), Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536321")] public async Task KeywordTypeParameters(TestHost testHost) { var code = @"class C<int> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(536853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536853")] public async Task TypeParametersWithAttribute(TestHost testHost) { var code = @"class C<[Attr] T> { }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, Punctuation.OpenBracket, Identifier("Attr"), Punctuation.CloseBracket, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration1(TestHost testHost) { var code = "class C1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ClassTypeDeclaration2(TestHost testHost) { var code = "class ClassName1 { } "; await TestAsync(code, testHost, Keyword("class"), Class("ClassName1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task StructTypeDeclaration1(TestHost testHost) { var code = "struct Struct1 { }"; await TestAsync(code, testHost, Keyword("struct"), Struct("Struct1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterfaceDeclaration1(TestHost testHost) { var code = "interface I1 { }"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task EnumDeclaration1(TestHost testHost) { var code = "enum Weekday { }"; await TestAsync(code, testHost, Keyword("enum"), Enum("Weekday"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(4302, "DevDiv_Projects/Roslyn")] [Theory] [CombinatorialData] public async Task ClassInEnum(TestHost testHost) { var code = "enum E { Min = System.Int32.MinValue }"; await TestAsync(code, testHost, Keyword("enum"), Enum("E"), Punctuation.OpenCurly, EnumMember("Min"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Int32"), Operators.Dot, Identifier("MinValue"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task DelegateDeclaration1(TestHost testHost) { var code = "delegate void Action();"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("Action"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task GenericTypeArgument(TestHost testHost) { await TestInMethodAsync( "C<T>", "M", "default(T)", testHost, Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task GenericParameter(TestHost testHost) { var code = "class C1<P1> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameters(TestHost testHost) { var code = "class C1<P1,P2> {}"; await TestAsync(code, testHost, Keyword("class"), Class("C1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.Comma, TypeParameter("P2"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Interface(TestHost testHost) { var code = "interface I1<P1> {}"; await TestAsync(code, testHost, Keyword("interface"), Interface("I1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Struct(TestHost testHost) { var code = "struct S1<P1> {}"; await TestAsync(code, testHost, Keyword("struct"), Struct("S1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Delegate(TestHost testHost) { var code = "delegate void D1<P1> {}"; await TestAsync(code, testHost, Keyword("delegate"), Keyword("void"), Delegate("D1"), Punctuation.OpenAngle, TypeParameter("P1"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task GenericParameter_Method(TestHost testHost) { await TestInClassAsync( @"T M<T>(T t) { return default(T); }", testHost, Identifier("T"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Identifier("T"), Parameter("t"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("default"), Punctuation.OpenParen, Identifier("T"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TernaryExpression(TestHost testHost) { await TestInExpressionAsync("true ? 1 : 0", testHost, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0")); } [Theory] [CombinatorialData] public async Task BaseClass(TestHost testHost) { await TestAsync( @"class C : B { }", testHost, Keyword("class"), Class("C"), Punctuation.Colon, Identifier("B"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestLabel(TestHost testHost) { await TestInMethodAsync("goo:", testHost, Label("goo"), Punctuation.Colon); } [Theory] [CombinatorialData] public async Task Attribute(TestHost testHost) { await TestAsync( @"[assembly: Goo]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task TestAngleBracketsOnGenericConstraints_Bug932262(TestHost testHost) { await TestAsync( @"class C<T> where T : A<T> { }", testHost, Keyword("class"), Class("C"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Identifier("A"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestYieldPositive(TestHost testHost) { await TestInMethodAsync( @"yield return goo;", testHost, ControlKeyword("yield"), ControlKeyword("return"), Identifier("goo"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestYieldNegative(TestHost testHost) { await TestInMethodAsync( @"int yield;", testHost, Keyword("int"), Local("yield"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestFromPositive(TestHost testHost) { await TestInExpressionAsync( @"from x in y", testHost, Keyword("from"), Identifier("x"), Keyword("in"), Identifier("y")); } [Theory] [CombinatorialData] public async Task TestFromNegative(TestHost testHost) { await TestInMethodAsync( @"int from;", testHost, Keyword("int"), Local("from"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersModule(TestHost testHost) { await TestAsync( @"[module: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("module"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersAssembly(TestHost testHost) { await TestAsync( @"[assembly: Obsolete]", testHost, Punctuation.OpenBracket, Keyword("assembly"), Punctuation.Colon, Identifier("Obsolete"), Punctuation.CloseBracket); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDelegate(TestHost testHost) { await TestInClassAsync( @"[type: A] [return: A] delegate void M();", testHost, Punctuation.OpenBracket, Keyword("type"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("delegate"), Keyword("void"), Delegate("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnMethod(TestHost testHost) { await TestInClassAsync( @"[return: A] [method: A] void M() { }", testHost, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnCtor(TestHost testHost) { await TestAsync( @"class C { [method: A] C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnDtor(TestHost testHost) { await TestAsync( @"class C { [method: A] ~C() { } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Operators.Tilde, Class("C"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnOperator(TestHost testHost) { await TestInClassAsync( @"[method: A] [return: A] static T operator +(T a, T b) { }", testHost, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("static"), Identifier("T"), Keyword("operator"), Operators.Plus, Punctuation.OpenParen, Identifier("T"), Parameter("a"), Punctuation.Comma, Identifier("T"), Parameter("b"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnEventDeclaration(TestHost testHost) { await TestInClassAsync( @"[event: A] event A E { [param: Test] [method: Test] add { } [param: Test] [method: Test] remove { } }", testHost, Punctuation.OpenBracket, Keyword("event"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("event"), Identifier("A"), Event("E"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("add"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("Test"), Punctuation.CloseBracket, Keyword("remove"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnPropertyAccessors(TestHost testHost) { await TestInClassAsync( @"int P { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Property("P"), Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexers(TestHost testHost) { await TestInClassAsync( @"[property: A] int this[int i] { get; set; }", testHost, Punctuation.OpenBracket, Keyword("property"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Keyword("get"), Punctuation.Semicolon, Keyword("set"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnIndexerAccessors(TestHost testHost) { await TestInClassAsync( @"int this[int i] { [return: T] [method: T] get { } [param: T] [method: T] set { } }", testHost, Keyword("int"), Keyword("this"), Punctuation.OpenBracket, Keyword("int"), Parameter("i"), Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenBracket, Keyword("return"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("get"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.OpenBracket, Keyword("param"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Punctuation.OpenBracket, Keyword("method"), Punctuation.Colon, Identifier("T"), Punctuation.CloseBracket, Keyword("set"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task AttributeTargetSpecifiersOnField(TestHost testHost) { await TestInClassAsync( @"[field: A] const int a = 0;", testHost, Punctuation.OpenBracket, Keyword("field"), Punctuation.Colon, Identifier("A"), Punctuation.CloseBracket, Keyword("const"), Keyword("int"), Constant("a"), Static("a"), Operators.Equals, Number("0"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestAllKeywords(TestHost testHost) { await TestAsync( @"using System; #region TaoRegion namespace MyNamespace { abstract class Goo : Bar { bool goo = default(bool); byte goo1; char goo2; const int goo3 = 999; decimal goo4; delegate void D(); delegate* managed<int, int> mgdfun; delegate* unmanaged<int, int> unmgdfun; double goo5; enum MyEnum { one, two, three }; event D MyEvent; float goo6; static int x; long goo7; sbyte goo8; short goo9; int goo10 = sizeof(int); string goo11; uint goo12; ulong goo13; volatile ushort goo14; struct SomeStruct { } protected virtual void someMethod() { } public Goo(int i) { bool var = i is int; try { while (true) { continue; break; } switch (goo) { case true: break; default: break; } } catch (System.Exception) { } finally { } checked { int i2 = 10000; i2++; } do { } while (true); if (false) { } else { } unsafe { fixed (int* p = &x) { } char* buffer = stackalloc char[16]; } for (int i1 = 0; i1 < 10; i1++) { } System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (object o in al) { object o1 = o; } lock (this) { } } Goo method(Bar i, out int z) { z = 5; return i as Goo; } public static explicit operator Goo(int i) { return new Baz(1); } public static implicit operator Goo(double x) { return new Baz(1); } public extern void doSomething(); internal void method2(object o) { if (o == null) goto Output; if (o is Baz) return; else throw new System.Exception(); Output: Console.WriteLine(""Finished""); } } sealed class Baz : Goo { readonly int field; public Baz(int i) : base(i) { } public void someOtherMethod(ref int i, System.Type c) { int f = 1; someOtherMethod(ref f, typeof(int)); } protected override void someMethod() { unchecked { int i = 1; i++; } } private void method(params object[] args) { } private string aMethod(object o) => o switch { int => string.Empty, _ when true => throw new System.Exception() }; } interface Bar { } } #endregion TaoRegion", testHost, new[] { new CSharpParseOptions(LanguageVersion.CSharp8) }, Keyword("using"), Identifier("System"), Punctuation.Semicolon, PPKeyword("#"), PPKeyword("region"), PPText("TaoRegion"), Keyword("namespace"), Namespace("MyNamespace"), Punctuation.OpenCurly, Keyword("abstract"), Keyword("class"), Class("Goo"), Punctuation.Colon, Identifier("Bar"), Punctuation.OpenCurly, Keyword("bool"), Field("goo"), Operators.Equals, Keyword("default"), Punctuation.OpenParen, Keyword("bool"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("byte"), Field("goo1"), Punctuation.Semicolon, Keyword("char"), Field("goo2"), Punctuation.Semicolon, Keyword("const"), Keyword("int"), Constant("goo3"), Static("goo3"), Operators.Equals, Number("999"), Punctuation.Semicolon, Keyword("decimal"), Field("goo4"), Punctuation.Semicolon, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("managed"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("mgdfun"), Punctuation.Semicolon, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("unmgdfun"), Punctuation.Semicolon, Keyword("double"), Field("goo5"), Punctuation.Semicolon, Keyword("enum"), Enum("MyEnum"), Punctuation.OpenCurly, EnumMember("one"), Punctuation.Comma, EnumMember("two"), Punctuation.Comma, EnumMember("three"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("event"), Identifier("D"), Event("MyEvent"), Punctuation.Semicolon, Keyword("float"), Field("goo6"), Punctuation.Semicolon, Keyword("static"), Keyword("int"), Field("x"), Static("x"), Punctuation.Semicolon, Keyword("long"), Field("goo7"), Punctuation.Semicolon, Keyword("sbyte"), Field("goo8"), Punctuation.Semicolon, Keyword("short"), Field("goo9"), Punctuation.Semicolon, Keyword("int"), Field("goo10"), Operators.Equals, Keyword("sizeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("string"), Field("goo11"), Punctuation.Semicolon, Keyword("uint"), Field("goo12"), Punctuation.Semicolon, Keyword("ulong"), Field("goo13"), Punctuation.Semicolon, Keyword("volatile"), Keyword("ushort"), Field("goo14"), Punctuation.Semicolon, Keyword("struct"), Struct("SomeStruct"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("protected"), Keyword("virtual"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Class("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("bool"), Local("var"), Operators.Equals, Identifier("i"), Keyword("is"), Keyword("int"), Punctuation.Semicolon, ControlKeyword("try"), Punctuation.OpenCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("continue"), Punctuation.Semicolon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("goo"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("true"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, ControlKeyword("default"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("finally"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("checked"), Punctuation.OpenCurly, Keyword("int"), Local("i2"), Operators.Equals, Number("10000"), Punctuation.Semicolon, Identifier("i2"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("do"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("while"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Keyword("false"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("else"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("unsafe"), Punctuation.OpenCurly, Keyword("fixed"), Punctuation.OpenParen, Keyword("int"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("x"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("char"), Operators.Asterisk, Local("buffer"), Operators.Equals, Keyword("stackalloc"), Keyword("char"), Punctuation.OpenBracket, Number("16"), Punctuation.CloseBracket, Punctuation.Semicolon, Punctuation.CloseCurly, ControlKeyword("for"), Punctuation.OpenParen, Keyword("int"), Local("i1"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("i1"), Operators.LessThan, Number("10"), Punctuation.Semicolon, Identifier("i1"), Operators.PlusPlus, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Local("al"), Operators.Equals, Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("ArrayList"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, ControlKeyword("foreach"), Punctuation.OpenParen, Keyword("object"), Local("o"), ControlKeyword("in"), Identifier("al"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("object"), Local("o1"), Operators.Equals, Identifier("o"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("lock"), Punctuation.OpenParen, Keyword("this"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Identifier("Goo"), Method("method"), Punctuation.OpenParen, Identifier("Bar"), Parameter("i"), Punctuation.Comma, Keyword("out"), Keyword("int"), Parameter("z"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("z"), Operators.Equals, Number("5"), Punctuation.Semicolon, ControlKeyword("return"), Identifier("i"), Keyword("as"), Identifier("Goo"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("explicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("static"), Keyword("implicit"), Keyword("operator"), Identifier("Goo"), Punctuation.OpenParen, Keyword("double"), Parameter("x"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("new"), Identifier("Baz"), Punctuation.OpenParen, Number("1"), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("public"), Keyword("extern"), Keyword("void"), Method("doSomething"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("internal"), Keyword("void"), Method("method2"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Operators.EqualsEquals, Keyword("null"), Punctuation.CloseParen, ControlKeyword("goto"), Identifier("Output"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("o"), Keyword("is"), Identifier("Baz"), Punctuation.CloseParen, ControlKeyword("return"), Punctuation.Semicolon, ControlKeyword("else"), ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Label("Output"), Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, String(@"""Finished"""), Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("sealed"), Keyword("class"), Class("Baz"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenCurly, Keyword("readonly"), Keyword("int"), Field("field"), Punctuation.Semicolon, Keyword("public"), Class("Baz"), Punctuation.OpenParen, Keyword("int"), Parameter("i"), Punctuation.CloseParen, Punctuation.Colon, Keyword("base"), Punctuation.OpenParen, Identifier("i"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("void"), Method("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Keyword("int"), Parameter("i"), Punctuation.Comma, Identifier("System"), Operators.Dot, Identifier("Type"), Parameter("c"), Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Local("f"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("someOtherMethod"), Punctuation.OpenParen, Keyword("ref"), Identifier("f"), Punctuation.Comma, Keyword("typeof"), Punctuation.OpenParen, Keyword("int"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("protected"), Keyword("override"), Keyword("void"), Method("someMethod"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("unchecked"), Punctuation.OpenCurly, Keyword("int"), Local("i"), Operators.Equals, Number("1"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("void"), Method("method"), Punctuation.OpenParen, Keyword("params"), Keyword("object"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("private"), Keyword("string"), Method("aMethod"), Punctuation.OpenParen, Keyword("object"), Parameter("o"), Punctuation.CloseParen, Operators.EqualsGreaterThan, Identifier("o"), ControlKeyword("switch"), Punctuation.OpenCurly, Keyword("int"), Operators.EqualsGreaterThan, Keyword("string"), Operators.Dot, Identifier("Empty"), Punctuation.Comma, Keyword("_"), ControlKeyword("when"), Keyword("true"), Operators.EqualsGreaterThan, ControlKeyword("throw"), Keyword("new"), Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("interface"), Interface("Bar"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, PPKeyword("#"), PPKeyword("endregion"), PPText("TaoRegion")); } [Theory] [CombinatorialData] public async Task TestAllOperators(TestHost testHost) { await TestAsync( @"using IO = System.IO; public class Goo<T> { public void method() { int[] a = new int[5]; int[] var = { 1, 2, 3, 4, 5 }; int i = a[i]; Goo<T> f = new Goo<int>(); f.method(); i = i + i - i * i / i % i & i | i ^ i; bool b = true & false | true ^ false; b = !b; i = ~i; b = i < i && i > i; int? ii = 5; int f = true ? 1 : 0; i++; i--; b = true && false || true; i << 5; i >> 5; b = i == i && i != i && i <= i && i >= i; i += 5.0; i -= i; i *= i; i /= i; i %= i; i &= i; i |= i; i ^= i; i <<= i; i >>= i; i ??= i; object s = x => x + 1; Point point; unsafe { Point* p = &point; p->x = 10; } IO::BinaryReader br = null; } }", testHost, Keyword("using"), Identifier("IO"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("IO"), Punctuation.Semicolon, Keyword("public"), Keyword("class"), Class("Goo"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Keyword("public"), Keyword("void"), Method("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("a"), Operators.Equals, Keyword("new"), Keyword("int"), Punctuation.OpenBracket, Number("5"), Punctuation.CloseBracket, Punctuation.Semicolon, Keyword("int"), Punctuation.OpenBracket, Punctuation.CloseBracket, Local("var"), Operators.Equals, Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.Comma, Number("4"), Punctuation.Comma, Number("5"), Punctuation.CloseCurly, Punctuation.Semicolon, Keyword("int"), Local("i"), Operators.Equals, Identifier("a"), Punctuation.OpenBracket, Identifier("i"), Punctuation.CloseBracket, Punctuation.Semicolon, Identifier("Goo"), Punctuation.OpenAngle, Identifier("T"), Punctuation.CloseAngle, Local("f"), Operators.Equals, Keyword("new"), Identifier("Goo"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("f"), Operators.Dot, Identifier("method"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Identifier("i"), Operators.Equals, Identifier("i"), Operators.Plus, Identifier("i"), Operators.Minus, Identifier("i"), Operators.Asterisk, Identifier("i"), Operators.Slash, Identifier("i"), Operators.Percent, Identifier("i"), Operators.Ampersand, Identifier("i"), Operators.Bar, Identifier("i"), Operators.Caret, Identifier("i"), Punctuation.Semicolon, Keyword("bool"), Local("b"), Operators.Equals, Keyword("true"), Operators.Ampersand, Keyword("false"), Operators.Bar, Keyword("true"), Operators.Caret, Keyword("false"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Operators.Exclamation, Identifier("b"), Punctuation.Semicolon, Identifier("i"), Operators.Equals, Operators.Tilde, Identifier("i"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.LessThan, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThan, Identifier("i"), Punctuation.Semicolon, Keyword("int"), Operators.QuestionMark, Local("ii"), Operators.Equals, Number("5"), Punctuation.Semicolon, Keyword("int"), Local("f"), Operators.Equals, Keyword("true"), Operators.QuestionMark, Number("1"), Operators.Colon, Number("0"), Punctuation.Semicolon, Identifier("i"), Operators.PlusPlus, Punctuation.Semicolon, Identifier("i"), Operators.MinusMinus, Punctuation.Semicolon, Identifier("b"), Operators.Equals, Keyword("true"), Operators.AmpersandAmpersand, Keyword("false"), Operators.BarBar, Keyword("true"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThan, Number("5"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThan, Number("5"), Punctuation.Semicolon, Identifier("b"), Operators.Equals, Identifier("i"), Operators.EqualsEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.ExclamationEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.LessThanEquals, Identifier("i"), Operators.AmpersandAmpersand, Identifier("i"), Operators.GreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PlusEquals, Number("5.0"), Punctuation.Semicolon, Identifier("i"), Operators.MinusEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AsteriskEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.SlashEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.PercentEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.AmpersandEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.BarEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.CaretEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.LessThanLessThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.GreaterThanGreaterThanEquals, Identifier("i"), Punctuation.Semicolon, Identifier("i"), Operators.QuestionQuestionEquals, Identifier("i"), Punctuation.Semicolon, Keyword("object"), Local("s"), Operators.Equals, Parameter("x"), Operators.EqualsGreaterThan, Identifier("x"), Operators.Plus, Number("1"), Punctuation.Semicolon, Identifier("Point"), Local("point"), Punctuation.Semicolon, Keyword("unsafe"), Punctuation.OpenCurly, Identifier("Point"), Operators.Asterisk, Local("p"), Operators.Equals, Operators.Ampersand, Identifier("point"), Punctuation.Semicolon, Identifier("p"), Operators.MinusGreaterThan, Identifier("x"), Operators.Equals, Number("10"), Punctuation.Semicolon, Punctuation.CloseCurly, Identifier("IO"), Operators.ColonColon, Identifier("BinaryReader"), Local("br"), Operators.Equals, Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestPartialMethodWithNamePartial(TestHost testHost) { await TestAsync( @"partial class C { partial void partial(string bar); partial void partial(string baz) { } partial int Goo(); partial int Goo() { } public partial void partial void }", testHost, Keyword("partial"), Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("bar"), Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("void"), Method("partial"), Punctuation.OpenParen, Keyword("string"), Parameter("baz"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("partial"), Keyword("int"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("public"), Keyword("partial"), Keyword("void"), Field("partial"), Keyword("void"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ValueInSetterAndAnonymousTypePropertyName(TestHost testHost) { await TestAsync( @"class C { int P { set { var t = new { value = value }; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("P"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Keyword("var"), Local("t"), Operators.Equals, Keyword("new"), Punctuation.OpenCurly, Identifier("value"), Operators.Equals, Identifier("value"), Punctuation.CloseCurly, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(538680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538680")] [Theory] [CombinatorialData] public async Task TestValueInLabel(TestHost testHost) { await TestAsync( @"class C { int X { set { value: ; } } }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("int"), Property("X"), Punctuation.OpenCurly, Keyword("set"), Punctuation.OpenCurly, Label("value"), Punctuation.Colon, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541150")] [Theory] [CombinatorialData] public async Task TestGenericVar(TestHost testHost) { await TestAsync( @"using System; static class Program { static void Main() { var x = 1; } } class var<T> { }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("static"), Keyword("class"), Class("Program"), Static("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly); } [WorkItem(541154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541154")] [Theory] [CombinatorialData] public async Task TestInaccessibleVar(TestHost testHost) { await TestAsync( @"using System; class A { private class var { } } class B : A { static void Main() { var x = 1; } }", testHost, Keyword("using"), Identifier("System"), Punctuation.Semicolon, Keyword("class"), Class("A"), Punctuation.OpenCurly, Keyword("private"), Keyword("class"), Class("var"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("B"), Punctuation.Colon, Identifier("A"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(541613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541613")] [Theory] [CombinatorialData] public async Task TestEscapedVar(TestHost testHost) { await TestAsync( @"class Program { static void Main(string[] args) { @var v = 1; } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Identifier("@var"), Local("v"), Operators.Equals, Number("1"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(542432, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542432")] [Theory] [CombinatorialData] public async Task TestVar(TestHost testHost) { await TestAsync( @"class Program { class var<T> { } static var<int> GetVarT() { return null; } static void Main() { var x = GetVarT(); var y = new var<int>(); } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("class"), Class("var"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("static"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Method("GetVarT"), Static("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("return"), Keyword("null"), Punctuation.Semicolon, Punctuation.CloseCurly, Keyword("static"), Keyword("void"), Method("Main"), Static("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("GetVarT"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, Keyword("new"), Identifier("var"), Punctuation.OpenAngle, Keyword("int"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } [WorkItem(543123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543123")] [Theory] [CombinatorialData] public async Task TestVar2(TestHost testHost) { await TestAsync( @"class Program { void Main(string[] args) { foreach (var v in args) { } } }", testHost, Keyword("class"), Class("Program"), Punctuation.OpenCurly, Keyword("void"), Method("Main"), Punctuation.OpenParen, Keyword("string"), Punctuation.OpenBracket, Punctuation.CloseBracket, Parameter("args"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Local("v"), ControlKeyword("in"), Identifier("args"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task InterpolatedStrings1(TestHost testHost) { var code = @" var x = ""World""; var y = $""Hello, {x}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("x"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("y"), Operators.Equals, String("$\""), String("Hello, "), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings2(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, String("$\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, String(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, String("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task InterpolatedStrings3(TestHost testHost) { var code = @" var a = ""Hello""; var b = ""World""; var c = $@""{a}, {b}""; "; await TestInMethodAsync(code, testHost, Keyword("var"), Local("a"), Operators.Equals, String("\"Hello\""), Punctuation.Semicolon, Keyword("var"), Local("b"), Operators.Equals, String("\"World\""), Punctuation.Semicolon, Keyword("var"), Local("c"), Operators.Equals, Verbatim("$@\""), Punctuation.OpenCurly, Identifier("a"), Punctuation.CloseCurly, Verbatim(", "), Punctuation.OpenCurly, Identifier("b"), Punctuation.CloseCurly, Verbatim("\""), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ExceptionFilter1(TestHost testHost) { var code = @" try { } catch when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task ExceptionFilter2(TestHost testHost) { var code = @" try { } catch (System.Exception) when (true) { } "; await TestInMethodAsync(code, testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("System"), Operators.Dot, Identifier("Exception"), Punctuation.CloseParen, ControlKeyword("when"), Punctuation.OpenParen, Keyword("true"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task OutVar(TestHost testHost) { var code = @" F(out var);"; await TestInMethodAsync(code, testHost, Identifier("F"), Punctuation.OpenParen, Keyword("out"), Identifier("var"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task ReferenceDirective(TestHost testHost) { var code = @" #r ""file.dll"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("r"), String("\"file.dll\"")); } [Theory] [CombinatorialData] public async Task LoadDirective(TestHost testHost) { var code = @" #load ""file.csx"""; await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("load"), String("\"file.csx\"")); } [Theory] [CombinatorialData] public async Task IncompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Keyword("await"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task CompleteAwaitInNonAsyncContext(TestHost testHost) { var code = @" void M() { var x = await; }"; await TestInClassAsync(code, testHost, Keyword("void"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("var"), Local("x"), Operators.Equals, Identifier("await"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TupleDeclaration(TestHost testHost) { await TestInMethodAsync("(int, string) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Punctuation.Comma, Keyword("string"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleDeclarationWithNames(TestHost testHost) { await TestInMethodAsync("(int a, string b) x", testHost, ParseOptions(TestOptions.Regular, Options.Script), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("string"), Identifier("b"), Punctuation.CloseParen, Local("x")); } [Theory] [CombinatorialData] public async Task TupleLiteral(TestHost testHost) { await TestInMethodAsync("var values = (1, 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TupleLiteralWithNames(TestHost testHost) { await TestInMethodAsync("var values = (a: 1, b: 2)", testHost, ParseOptions(TestOptions.Regular, Options.Script), Keyword("var"), Local("values"), Operators.Equals, Punctuation.OpenParen, Identifier("a"), Punctuation.Colon, Number("1"), Punctuation.Comma, Identifier("b"), Punctuation.Colon, Number("2"), Punctuation.CloseParen); } [Theory] [CombinatorialData] public async Task TestConflictMarkers1(TestHost testHost) { await TestAsync( @"class C { <<<<<<< Start public void Goo(); ======= public void Bar(); >>>>>>> End }", testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Comment("<<<<<<< Start"), Keyword("public"), Keyword("void"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment("======="), Keyword("public"), Keyword("void"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Semicolon, Comment(">>>>>>> End"), Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var unmanaged = 0; unmanaged++;", testHost, Keyword("var"), Local("unmanaged"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("unmanaged"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : unmanaged { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X<T> where T : unmanaged { }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X<T> where T : unmanaged { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void M<T>() where T : unmanaged { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : unmanaged;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} delegate void D<T>() where T : unmanaged;", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } delegate void D<T>() where T : unmanaged;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface unmanaged {} class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestUnmanagedConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface unmanaged {} } class X { void N() { void M<T>() where T : unmanaged { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("unmanaged"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationIsPattern(TestHost testHost) { await TestInMethodAsync(@" object foo; if (foo is Action action) { }", testHost, Keyword("object"), Local("foo"), Punctuation.Semicolon, ControlKeyword("if"), Punctuation.OpenParen, Identifier("foo"), Keyword("is"), Identifier("Action"), Local("action"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationSwitchPattern(TestHost testHost) { await TestInMethodAsync(@" object y; switch (y) { case int x: break; }", testHost, Keyword("object"), Local("y"), Punctuation.Semicolon, ControlKeyword("switch"), Punctuation.OpenParen, Identifier("y"), Punctuation.CloseParen, Punctuation.OpenCurly, ControlKeyword("case"), Keyword("int"), Local("x"), Punctuation.Colon, ControlKeyword("break"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestDeclarationExpression(TestHost testHost) { await TestInMethodAsync(@" int (foo, bar) = (1, 2);", testHost, Keyword("int"), Punctuation.OpenParen, Local("foo"), Punctuation.Comma, Local("bar"), Punctuation.CloseParen, Operators.Equals, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestTupleTypeSyntax(TestHost testHost) { await TestInClassAsync(@" public (int a, int b) Get() => null;", testHost, Keyword("public"), Punctuation.OpenParen, Keyword("int"), Identifier("a"), Punctuation.Comma, Keyword("int"), Identifier("b"), Punctuation.CloseParen, Method("Get"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.EqualsGreaterThan, Keyword("null"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestOutParameter(TestHost testHost) { await TestInMethodAsync(@" if (int.TryParse(""1"", out int x)) { }", testHost, ControlKeyword("if"), Punctuation.OpenParen, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestOutParameter2(TestHost testHost) { await TestInClassAsync(@" int F = int.TryParse(""1"", out int x) ? x : -1; ", testHost, Keyword("int"), Field("F"), Operators.Equals, Keyword("int"), Operators.Dot, Identifier("TryParse"), Punctuation.OpenParen, String(@"""1"""), Punctuation.Comma, Keyword("out"), Keyword("int"), Local("x"), Punctuation.CloseParen, Operators.QuestionMark, Identifier("x"), Operators.Colon, Operators.Minus, Number("1"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingDirective(TestHost testHost) { var code = @"using System.Collections.Generic;"; await TestAsync(code, testHost, Keyword("using"), Identifier("System"), Operators.Dot, Identifier("Collections"), Operators.Dot, Identifier("Generic"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForIdentifier(TestHost testHost) { var code = @"using Col = System.Collections;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Col"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Collections"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingAliasDirectiveForClass(TestHost testHost) { var code = @"using Con = System.Console;"; await TestAsync(code, testHost, Keyword("using"), Identifier("Con"), Operators.Equals, Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestUsingStaticDirective(TestHost testHost) { var code = @"using static System.Console;"; await TestAsync(code, testHost, Keyword("using"), Keyword("static"), Identifier("System"), Operators.Dot, Identifier("Console"), Punctuation.Semicolon); } [WorkItem(33039, "https://github.com/dotnet/roslyn/issues/33039")] [Theory] [CombinatorialData] public async Task ForEachVariableStatement(TestHost testHost) { await TestInMethodAsync(@" foreach (var (x, y) in new[] { (1, 2) }); ", testHost, ControlKeyword("foreach"), Punctuation.OpenParen, Identifier("var"), Punctuation.OpenParen, Local("x"), Punctuation.Comma, Local("y"), Punctuation.CloseParen, ControlKeyword("in"), Keyword("new"), Punctuation.OpenBracket, Punctuation.CloseBracket, Punctuation.OpenCurly, Punctuation.OpenParen, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Punctuation.CloseCurly, Punctuation.CloseParen, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task CatchDeclarationStatement(TestHost testHost) { await TestInMethodAsync(@" try { } catch (Exception ex) { } ", testHost, ControlKeyword("try"), Punctuation.OpenCurly, Punctuation.CloseCurly, ControlKeyword("catch"), Punctuation.OpenParen, Identifier("Exception"), Local("ex"), Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_InsideMethod(TestHost testHost) { await TestInMethodAsync(@" var notnull = 0; notnull++;", testHost, Keyword("var"), Local("notnull"), Operators.Equals, Number("0"), Punctuation.Semicolon, Identifier("notnull"), Operators.PlusPlus, Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_Keyword(TestHost testHost) { await TestAsync( "class X<T> where T : notnull { }", testHost, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X<T> where T : notnull { }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Type_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X<T> where T : notnull { }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_Keyword(TestHost testHost) { await TestAsync(@" class X { void M<T>() where T : notnull { } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void M<T>() where T : notnull { } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Method_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void M<T>() where T : notnull { } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_Keyword(TestHost testHost) { await TestAsync( "delegate void D<T>() where T : notnull;", testHost, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} delegate void D<T>() where T : notnull;", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_Delegate_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } delegate void D<T>() where T : notnull;", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("delegate"), Keyword("void"), Delegate("D"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.Semicolon); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_Keyword(TestHost testHost) { await TestAsync(@" class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterface(TestHost testHost) { await TestAsync(@" interface notnull {} class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] public async Task TestNotNullConstraint_LocalFunction_ExistingInterfaceButOutOfScope(TestHost testHost) { await TestAsync(@" namespace OtherScope { interface notnull {} } class X { void N() { void M<T>() where T : notnull { } } }", testHost, Keyword("namespace"), Namespace("OtherScope"), Punctuation.OpenCurly, Keyword("interface"), Interface("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Keyword("class"), Class("X"), Punctuation.OpenCurly, Keyword("void"), Method("N"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("void"), Method("M"), Punctuation.OpenAngle, TypeParameter("T"), Punctuation.CloseAngle, Punctuation.OpenParen, Punctuation.CloseParen, Keyword("where"), Identifier("T"), Punctuation.Colon, Keyword("notnull"), Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory] [CombinatorialData] [WorkItem(45807, "https://github.com/dotnet/roslyn/issues/45807")] public async Task FunctionPointer(TestHost testHost) { var code = @" class C { delegate* unmanaged[Stdcall, SuppressGCTransition] <int, int> x; }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("delegate"), Operators.Asterisk, Keyword("unmanaged"), Punctuation.OpenBracket, Identifier("Stdcall"), Punctuation.Comma, Identifier("SuppressGCTransition"), Punctuation.CloseBracket, Punctuation.OpenAngle, Keyword("int"), Punctuation.Comma, Keyword("int"), Punctuation.CloseAngle, Field("x"), Punctuation.Semicolon, Punctuation.CloseCurly); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan1() { var source = @"/// <param name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(0, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(3, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(4, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(5, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(11, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(15, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(16, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(17, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(24, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(26, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 1)) }, classifications); } [Fact, WorkItem(48094, "https://github.com/dotnet/roslyn/issues/48094")] public async Task TestXmlAttributeNameSpan2() { var source = @" /// <param /// name=""value""></param>"; using var workspace = CreateWorkspace(source, options: null, TestHost.InProcess); var document = workspace.CurrentSolution.Projects.First().Documents.First(); var classifications = await GetSyntacticClassificationsAsync(document, new TextSpan(0, source.Length)); Assert.Equal(new[] { new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(2, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentText, new TextSpan(5, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(6, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(7, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(14, 3)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeName, new TextSpan(18, 4)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(22, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(23, 1)), new ClassifiedSpan(ClassificationTypeNames.Identifier, new TextSpan(24, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentAttributeQuotes, new TextSpan(29, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(30, 1)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(31, 2)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentName, new TextSpan(33, 5)), new ClassifiedSpan(ClassificationTypeNames.XmlDocCommentDelimiter, new TextSpan(38, 1)) }, classifications); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestStaticLocalFunction(TestHost testHost) { var code = @" class C { public static void M() { static void LocalFunc() { } } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("static"), Keyword("void"), Method("LocalFunc"), Static("LocalFunc"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Punctuation.CloseCurly, Punctuation.CloseCurly, Punctuation.CloseCurly); } [Theory, WorkItem(52290, "https://github.com/dotnet/roslyn/issues/52290")] [CombinatorialData] public async Task TestConstantLocalVariable(TestHost testHost) { var code = @" class C { public static void M() { const int Zero = 0; } }"; await TestAsync(code, testHost, Keyword("class"), Class("C"), Punctuation.OpenCurly, Keyword("public"), Keyword("static"), Keyword("void"), Method("M"), Static("M"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.OpenCurly, Keyword("const"), Keyword("int"), Constant("Zero"), Static("Zero"), Operators.Equals, Number("0"), Punctuation.Semicolon, Punctuation.CloseCurly, Punctuation.CloseCurly); } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { [UseExportProvider] public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SymbolCompletionProvider); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestExperimentationService)); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFile(SourceCodeKind sourceCodeKind) { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind) { await VerifyItemExistsAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashR() => await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashLoad() => await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirective() { await VerifyItemIsAbsentAsync(@"using $$", @"String"); await VerifyItemIsAbsentAsync(@"using $$ = System", @"System"); await VerifyItemExistsAsync(@"using $$", @"System"); await VerifyItemExistsAsync(@"using T = $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegionWithUsing() { await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegionWithUsing() { await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineXmlComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenCharLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute1() { await VerifyItemExistsAsync(@"[assembly: $$]", @"System"); await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SystemAttributeIsNotAnAttribute() { var content = @"[$$] class CL {}"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeAttribute() { var content = @"[$$] class CL {}"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAttribute() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodAttribute() { var content = @"class CL { [$$] void Method() {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodTypeParamAttribute() { var content = @"class CL{ void Method<[A$$]T> () {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamAttribute() { var content = @"class CL{ void Method ([$$]int i) {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_TopLevel() { var source = @"namespace $$ { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_Nested() { var source = @"; namespace System { namespace $$ { } }"; await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers() { var source = @"using System; namespace $$"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelWithPeer() { var source = @" namespace A { } namespace $$"; await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithNoPeers() { var source = @" namespace A { namespace $$ }"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithPeer() { var source = @" namespace A { namespace B { } namespace $$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() { var source = @"namespace N$$S"; await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNested() { var source = @" namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace $$ namespace C1 { } } namespace B.C2 { } } namespace A.B.C3 { }"; // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // C1 => A.B.?.C1 // C2 => A.B.B.C2 // C3 => A.A.B.C3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); // Because of the above, B does end up in the completion list // since A.B.B appears to be a peer of the new declaration await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NoPeers() { var source = @"namespace A.$$"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer() { var source = @" namespace A.B { } namespace A.$$"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NestedWithPeer() { var source = @" namespace A { namespace B.C { } namespace B.$$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNested() { var source = @" namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem.Runtime { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnKeyword() { var source = @"name$$space System { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnNestedKeyword() { var source = @" namespace System { name$$space Runtime { } }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace C.$$ namespace C.D1 { } } namespace B.C.D2 { } } namespace A.B.C.D3 { }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); // Ideally, all the D* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // D1 => A.B.C.C.?.D1 // D2 => A.B.B.C.D2 // D3 => A.A.B.C.D3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnderNamespace() { await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType1() { await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType2() { var content = @"namespace NS { class CL {} $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideProperty() { var content = @"class C { private string name; public string Name { set { name = $$"; await VerifyItemExistsAsync(content, @"value"); await VerifyItemExistsAsync(content, @"C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDot() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingAlias() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMember() { var content = @"class CL { $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMemberAccessibility() { var content = @"class CL { public $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BadStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameter() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionTypePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StackAllocArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseTypeOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DeclarationStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VariableDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementNoToken() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldDeclaration() { var content = @"class CL { $$ i"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventFieldDeclaration() { var content = @"class CL { event $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclaration() { var content = @"class CL { explicit operator $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclarationNoToken() { var content = @"class CL { explicit $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PropertyDeclaration() { var content = @"class CL { $$ Prop {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventDeclaration() { var content = @"class CL { event $$ Event {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerDeclaration() { var content = @"class CL { $$ this"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter() { var content = @"class CL { void Method($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayType() { var content = @"class CL { $$ ["; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PointerType() { var content = @"class CL { $$ *"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableType() { var content = @"class CL { $$ ?"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateDeclaration() { var content = @"class CL { delegate $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration() { var content = @"class CL { $$ M("; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OperatorDeclaration() { var content = @"class CL { $$ operator"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Argument() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseInPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LetClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OrderingExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SelectClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThrowStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System"); } [WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YieldReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LockStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EqualsValueClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementInitializersPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementConditionOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementIncrementorsPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhileStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayRankSpecifierSizesPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrefixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PostfixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenTruePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenFalsePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseInExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseLeftExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseRightExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhereClauseConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseGroupExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseByExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IfStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchLabelCase() { var content = @"switch(i) { case $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchPatternLabelCase() { var content = @"switch(i) { case $$ when"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionFirstBranch() { var content = @"i switch { $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionSecondBranch() { var content = @"i switch { 1 => true, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternFirstPosition() { var content = @"i is ($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternSecondPosition() { var content = @"i is (1, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternFirstPosition() { var content = @"i is { P: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternSecondPosition() { var content = @"i is { P1: 1, P2: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InitializerExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseList() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseAnotherWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause1() { await VerifyItemExistsAsync(@"class CL<T> where $$", @"T"); await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T"); await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause2() { await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause3() { await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1"); await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseListWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedName() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedNamespace() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedType() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstructorInitializer() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Checked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Unchecked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Locals() => await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameters() => await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AnonymousMethodDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommonTypesInNewExpressionContext() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionForUnboundTypes() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInTypeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInDefault() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInSizeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInGenericParameterList() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterNumericLiteral() { // NOTE: the Completion command handler will suppress this case if the user types '.', // but we still need to show members if the user specifically invokes statement completion here. await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterParenthesizedNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedNumericLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterArithmeticExpression() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals"); [WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceTypesAvailableInUsingAlias() => await VerifyItemExistsAsync(@"using S = System.$$", "String"); [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember1() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember2() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { this.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember3() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { base.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember1() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember2() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { B.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember3() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { A.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedInstanceAndStaticMembers() { var markup = @" class A { private static void HiddenStatic() { } protected static void GooStatic() { } private void HiddenInstance() { } protected void GooInstance() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "HiddenStatic"); await VerifyItemExistsAsync(markup, "GooStatic"); await VerifyItemIsAbsentAsync(markup, "HiddenInstance"); await VerifyItemExistsAsync(markup, "GooInstance"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer1() { var markup = @" class C { void M() { for (int i = 0; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer2() { var markup = @" class C { void M() { for (int i = 0; i < 10; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersInClass() { var markup = @" class C<T, R> { $$ } "; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(ref $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(out $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(in $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(ref String parameter) { M(ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(out String parameter) { M(out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(in String parameter) { M(in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefExpression_TypeAndVariable() { var markup = @" using System; class C { void M(String parameter) { ref var x = ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref readonly $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType1() { var markup = @" class Q { $$ class R { } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType2() { var markup = @" class Q { class R { $$ } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType3() { var markup = @" class Q { class R { } $$ } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Regular() { var markup = @" class Q { class R { } } $$"; // At EOF // Top-level statements are not allowed to follow classes, but we still offer it in completion for a few // reasons: // // 1. The code is simpler // 2. It's a relatively rare coding practice to define types outside of namespaces // 3. It allows the compiler to produce a better error message when users type things in the wrong order await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Script() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType5() { var markup = @" class Q { class R { } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType6() { var markup = @" class Q { class R { $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenTypeAndLocal() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void goo() { int i = 5; i.$$ List<string> ml = new List<string>(); } }"; await VerifyItemExistsAsync(markup, "CompareTo"); } [WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { AwaitTest test = new AwaitTest(); test.Test1().Wait(); } } class AwaitTest { List<string> stringList = new List<string>(); public async Task<bool> Test1() { stringList.$$ await Test2(); return true; } public async Task<bool> Test2() { return true; } }"; await VerifyItemExistsAsync(markup, "Add"); } [WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterNewInScript() { var markup = @" using System; new $$"; await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodsInScript() { var markup = @" using System.Linq; var a = new int[] { 1, 2 }; a.$$"; await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionsInForLoopInitializer() { var markup = @" public class C { public void M() { int count = 0; for ($$ "; await VerifyItemExistsAsync(markup, "count"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression1() { var markup = @" public class C { public void M() { System.Func<int, int> f = arg => { arg = 2; return arg; }.$$ } } "; await VerifyItemIsAbsentAsync(markup, "ToString"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression2() { var markup = @" public class C { public void M() { ((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$ } } "; await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemExistsAsync(markup, "Invoke"); } [WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InMultiLineCommentAtEndOfFile() { var markup = @" using System; /*$$"; await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersAtEndOfFile() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Outer<T> { class Inner<U> { static void F(T t, U u) { return; } public static void F(T t) { Outer<$$"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForCase() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "case 0:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "default:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchPresentForDefault() { var markup = @" class Program { static void Main() { int x; switch (x) { default: goto $$"; await VerifyItemExistsAsync(markup, "default"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto1() { var markup = @" class Program { static void Main() { Goo: int Goo; goto $$"; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto2() { var markup = @" class Program { static void Main() { Goo: int Goo; goto Goo $$"; await VerifyItemIsAbsentAsync(markup, "Goo"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeName() { var markup = @" using System; [$$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifier() { var markup = @" using System; [assembly:$$ "; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeList() { var markup = @" using System; [CLSCompliant, $$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameBeforeClass() { var markup = @" using System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifierBeforeClass() { var markup = @" using System; [assembly:$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeArgumentList() { var markup = @" using System; [CLSCompliant($$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInsideClass() { var markup = @" using System; class C { $$ }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName1() { var markup = @" using Alias = System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName2() { var markup = @" using Alias = Goo; namespace Goo { } [$$ class C { }"; await VerifyItemIsAbsentAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName3() { var markup = @" using Alias = Goo; namespace Goo { class A : System.Attribute { } } [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace() { var markup = @" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace2() { var markup = @" namespace Test { namespace Two { class MyAttribute : System.Attribute { } [Test.Two.$$ class Program { } } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task KeywordsUsedAsLocals() { var markup = @" class C { void M() { var error = 0; var method = 0; var @int = 0; Console.Write($$ } }"; // preprocessor keyword await VerifyItemExistsAsync(markup, "error"); await VerifyItemIsAbsentAsync(markup, "@error"); // contextual keyword await VerifyItemExistsAsync(markup, "method"); await VerifyItemIsAbsentAsync(markup, "@method"); // full keyword await VerifyItemExistsAsync(markup, "@int"); await VerifyItemIsAbsentAsync(markup, "int"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords1() { var markup = @" class C { void M() { var from = new[]{1,2,3}; var r = from x in $$ } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords2() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where $$ == @where.Length select @from; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords3() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where @from == @where.Length select $$; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAlias() { var markup = @" class MyAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() { var markup = @" class namespaceAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute1() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute2() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace2"); await VerifyItemExistsAsync(markup, "Namespace3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute3() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.$$]"; await VerifyItemExistsAsync(markup, "Namespace4"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute4() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.Namespace4.$$]"; await VerifyItemExistsAsync(markup, "Custom"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() { var markup = @" using Namespace1Alias = Namespace1; using Namespace2Alias = Namespace1.Namespace2; using Namespace3Alias = Namespace1.Namespace3; using Namespace4Alias = Namespace1.Namespace3.Namespace4; namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1Alias"); await VerifyItemIsAbsentAsync(markup, "Namespace2Alias"); await VerifyItemExistsAsync(markup, "Namespace3Alias"); await VerifyItemExistsAsync(markup, "Namespace4Alias"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithoutNestedAttribute() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } } } [$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace1"); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariableInQuerySelect() { var markup = @" using System.Linq; class P { void M() { var src = new string[] { ""Goo"", ""Bar"" }; var q = from x in src select x.$$"; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsPatternExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ 1"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchPatternCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$ when"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchGotoCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case MAX_SIZE: break; case GOO: goto case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInEnumMember() { var markup = @" class C { public const int GOO = 0; enum E { A = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute1() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage($$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute2() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(GOO, $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute3() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(validOn: $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute4() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(AllowMultiple = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInParameterDefaultValue() { var markup = @" class C { public const int GOO = 0; void M(int x = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstField() { var markup = @" class C { public const int GOO = 0; const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstLocal() { var markup = @" class C { public const int GOO = 0; void M() { const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1Overload() { var markup = @" class C { void M(int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2Overloads() { var markup = @" class C { void M(int i) { } void M(out int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1GenericOverload() { var markup = @" class C { void M<T>(T i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2GenericOverloads() { var markup = @" class C { void M<T>(int i) { } void M<T>(out int i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionNamedGenericType() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionParameter() { var markup = @" class C<T> { void M(T goo) { $$"; await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionGenericTypeParameter() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionAnonymousType() { var markup = @" class C { void M() { var a = new { }; $$ "; var expectedDescription = $@"({FeaturesResources.local_variable}) 'a a {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}"; await VerifyItemExistsAsync(markup, "a", expectedDescription); } [WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterNewInAnonymousType() { var markup = @" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } "; await VerifyItemExistsAsync(markup, "Program"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticMethod() { var markup = @" class C { int x = 0; static void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticFieldInitializer() { var markup = @" class C { int x = 0; static int y = $$ } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticMethod() { var markup = @" class C { static int x = 0; static void M() { $$ } } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticFieldInitializer() { var markup = @" class C { static int x = 0; static int y = $$ } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { int i; class inner { void M() { $$ } } } "; await VerifyItemIsAbsentAsync(markup, "i"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { static int i; class inner { void M() { $$ } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyEnumMembersInEnumMemberAccess() { var markup = @" class C { enum x {a,b,c} void M() { x.$$ } } "; await VerifyItemExistsAsync(markup, "a"); await VerifyItemExistsAsync(markup, "b"); await VerifyItemExistsAsync(markup, "c"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoEnumMembersInEnumLocalAccess() { var markup = @" class C { enum x {a,b,c} void M() { var y = x.a; y.$$ } } "; await VerifyItemIsAbsentAsync(markup, "a"); await VerifyItemIsAbsentAsync(markup, "b"); await VerifyItemIsAbsentAsync(markup, "c"); await VerifyItemExistsAsync(markup, "Equals"); } [WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaParameterDot() { var markup = @" using System; using System.Linq; class A { public event Func<String, String> E; } class Program { static void Main(string[] args) { new A().E += ss => ss.$$ } } "; await VerifyItemExistsAsync(markup, "Substring"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAtRoot_Interactive() { await VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterClass_Interactive() { await VerifyItemIsAbsentAsync( @"class C { } $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalStatement_Interactive() { await VerifyItemIsAbsentAsync( @"System.Console.WriteLine(); $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() { await VerifyItemIsAbsentAsync( @"int i = 0; $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInUsingAlias() { await VerifyItemIsAbsentAsync( @"using Goo = $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInEmptyStatement() { await VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideSetter() { await VerifyItemExistsAsync( @"class C { int Goo { set { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideAdder() { await VerifyItemExistsAsync( @"class C { event int Goo { add { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideRemover() { await VerifyItemExistsAsync( @"class C { event int Goo { remove { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterDot() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { this.$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterArrow() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a->$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterColonColon() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a::$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInGetter() { await VerifyItemIsAbsentAsync( @"class C { int Goo { get { $$", "value"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterNullableTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkAndPartialIdentifierInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskAndPartialIdentifierInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* f$$", "goo"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterEventFieldDeclaredInSameType() { await VerifyItemExistsAsync( @"class C { public event System.EventHandler E; void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterFullEventDeclaredInSameType() { await VerifyItemIsAbsentAsync( @"class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterEventDeclaredInDifferentType() { await VerifyItemIsAbsentAsync( @"class C { void M() { System.Console.CancelKeyPress.$$", "Invoke"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotInObjectInitializerMemberContext() { await VerifyItemIsAbsentAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$", "x"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task AfterPointerMemberAccess() { await VerifyItemExistsAsync(@" struct MyStruct { public int MyField; } class Program { static unsafe void Main(string[] args) { MyStruct s = new MyStruct(); MyStruct* ptr = &s; ptr->$$ }}", "MyField"); } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. [WorkItem(11931, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task VerbatimAttributes() { var code = @" using System; public class X : Attribute { } public class XAttribute : Attribute { } [@X$$] class Class3 { } "; await VerifyItemExistsAsync(code, "X"); await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute")); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; $$ } } ", "Console"); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for ($$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclaration() { // "int goo = goo = 1" is a legal declaration await VerifyItemExistsAsync(@" class Program { void M() { int goo = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclarator() { // "int bar = bar = 1" is legal in a declarator await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$, int baz = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclaration() { await VerifyItemIsAbsentAsync(@" class Program { void M() { $$ int goo = 0; } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclarator() { await VerifyItemIsAbsentAsync(@" class Program { void M() { int goo = $$, bar = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAfterDeclarator() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAsOutArgumentInInitializerExpression() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = Bar(out $$ } int Bar(out int x) { x = 3; return 5; } }", "goo"); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverriddenSymbolsFilteredFromCompletionList() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" public class B { public virtual void Goo(int original) { } } public class D : B { public override void Goo(int derived) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { C c = new C(); c.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Goo() { } } public class D : B { public void Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { $$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")] [WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")] [WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { public int Bar { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateNever() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAlways() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads1() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads2() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateNever() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAlways() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateNever() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAlways() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" public class Goo : Bar { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Bar { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAlways() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAdvanced() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Always() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Never() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 0, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestColorColor1() { var markup = @" class A { static void Goo() { } void Bar() { } static void Main() { A A = new A(); A.$$ } }"; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType1() { var markup = @" using System; class C { public static void Main() { $$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType2() { var markup = @" using System; class C { public static void Main() { C$$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "IndexProp", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } [WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDeclarationAmbiguity() { var markup = @" using System; class Program { void Main() { Environment.$$ var v; } }"; await VerifyItemExistsAsync(markup, "CommandLine"); } [WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldDeclarationAmbiguity() { var markup = @" using System; Environment.$$ var v; }"; await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCursorOnClassCloseBrace() { var markup = @" using System; class Outer { class Inner { } $$}"; await VerifyItemExistsAsync(markup, "Inner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync1() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync2() { var markup = @" using System.Threading.Tasks; class Program { public async T$$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterAsyncInMethodBody() { var markup = @" using System.Threading.Tasks; class Program { void goo() { var x = async $$ } }"; await VerifyItemIsAbsentAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable1() { var markup = @" class Program { void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable2() { var markup = @" class Program { async void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable1() { var markup = @" using System.Threading; using System.Threading.Tasks; class Program { async Task goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable2() { var markup = @" using System.Threading.Tasks; class Program { async Task<int> goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpression() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = await request.$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; // Nothing should be found: no awaiter for request. await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Task<Request>(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { $$ } }"; await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); } [WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersOnDottingIntoUnboundType() { var markup = @" class Program { RegistryKey goo; static void Main(string[] args) { goo.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeArgumentsInConstraintAfterBaselist() { var markup = @" public class Goo<T> : System.Object where $$ { }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDestructor() { var markup = @" class C { ~C() { $$ "; await VerifyItemIsAbsentAsync(markup, "Finalize"); } [WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodOnCovariantInterface() { var markup = @" class Schema<T> { } interface ISet<out T> { } static class SetMethods { public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { } } class Context { public ISet<T> Set<T>() { return null; } } class CustomSchema : Schema<int> { } class Program { static void Main(string[] args) { var set = new Context().Set<CustomSchema>(); set.$$ "; await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachInsideParentheses() { var markup = @" using System; class C { void M() { foreach($$) "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldInitializerInP2P() { var markup = @" class Class { int i = Consts.$$; }"; var referencedCode = @" public static class Consts { public const int C = 1; }"; await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false); } [WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowWithEqualsSign() { var markup = @" class c { public int value {set; get; }} class d { void goo() { c goo = new c { value$$= } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterThisDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { this.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { base.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInScriptContext() => await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); [WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoNestedTypeWhenDisplayingInstance() { var markup = @" class C { class D { } void M2() { new C().$$ } }"; await VerifyItemIsAbsentAsync(markup, "D"); } [WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchVariableInExceptionFilter() { var markup = @" class C { void M() { try { } catch (System.Exception myExn) when ($$"; await VerifyItemExistsAsync(markup, "myExn"); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterExternAlias() { var markup = @" class C { void goo() { global::$$ } }"; await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExternAliasSuggested() { var markup = @" extern alias Bar; class C { void goo() { $$ } }"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassDestructor() { var markup = @" class C { class N { ~$$ } }"; await VerifyItemExistsAsync(markup, "N"); await VerifyItemIsAbsentAsync(markup, "C"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TildeOutsideClass() { var markup = @" class C { class N { } } ~$$"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "N"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StructDestructor() { var markup = @" struct C { ~$$ }"; await VerifyItemIsAbsentAsync(markup, "C"); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("record")] [InlineData("record class")] public async Task RecordDestructor(string record) { var markup = $@" {record} C {{ ~$$ }}"; await VerifyItemExistsAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RecordStructDestructor() { var markup = $@" record struct C {{ ~$$ }}"; await VerifyItemIsAbsentAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { int x; void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { $$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR class G { public void DoGStuff() {} } #endif void goo() { new G().$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { int xyz; $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { #if PROJ1 int xyz; #endif $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { LABEL: int xyz; goto $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.label}) LABEL"; await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] { 1, 2, 3 } select $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); } [WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void Shared() { var x = GetThing(); x.$$ } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE public int x; #endif #if TWO public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({ FeaturesResources.field }) int C.x"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if TWO public int x; #endif #if ONE public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = "int C.x { get; set; }"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessWalkUp() { var markup = @" public class B { public A BA; public B BB; } class A { public A AA; public A AB; public int? x; public void goo() { A a = null; var q = a?.$$AB.BA.AB.BA; } }"; await VerifyItemExistsAsync(markup, "AA"); await VerifyItemExistsAsync(markup, "AB"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { A a = null; var q = a?.s?.$$; } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped2() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { var q = s?.$$i?.ToString(); } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt?.$$ } } "; await VerifyItemExistsAsync(markup, "Day"); await VerifyItemIsAbsentAsync(markup, "Value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableIsNotUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt.$$ } } "; await VerifyItemExistsAsync(markup, "Value"); await VerifyItemIsAbsentAsync(markup, "Day"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterConditionalIndexing() { var markup = @" public struct S { public int? i; } class A { public S[] s; public void goo() { A a = null; var q = a?.s?[$$; } }"; await VerifyItemExistsAsync(markup, "System"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses1() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.$$b?.c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses2() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.$$c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "c"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses3() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.c?.$$d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "d"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnSelf() { var markup = @"using System; [My] class X { [My$$] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnOuterType() { var markup = @"using System; [My] class Y { } [$$] class X { [My] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType() { var markup = @"abstract class Test { private int _field; public sealed class InnerTest : Test { public void SomeTest() { $$ } } }"; await VerifyItemExistsAsync(markup, "_field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType2() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { $$ // M recommended and accessible } class NN { void Test2() { // M inaccessible and not recommended } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType3() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN { void Test2() { $$ // M inaccessible and not recommended } } } }"; await VerifyItemIsAbsentAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType4() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN : N { void Test2() { $$ // M accessible and recommended. } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType5() { var markup = @" class D { public void Q() { } } class C<T> : D { class N { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "Q"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType6() { var markup = @" class Base<T> { public int X; } class Derived : Base<int> { class Nested { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "X"); } [WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoTypeParametersDefinedInCrefs() { var markup = @"using System; /// <see cref=""Program{T$$}""/> class Program<T> { }"; await VerifyItemIsAbsentAsync(markup, "T"); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList1() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList2() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<string,$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionInAliasedType() { var markup = @" using IAlias = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C { I$$ } "; await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinNameOf() { var markup = @" class C { void goo() { var x = nameof($$) } } "; await VerifyAnyItemExistsAsync(markup); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y1"); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y2"); } [WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteDeclarationExpressionType() { var markup = @" using System; class C { void goo() { var x = Console.$$ var y = 3; } } "; await VerifyItemExistsAsync(markup, "WriteLine"); } [WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticAndInstanceInNameOf() { var markup = @" using System; class C { class D { public int x; public static int y; } void goo() { var z = nameof(C.D.$$ } } "; await VerifyItemExistsAsync(markup, "x"); await VerifyItemExistsAsync(markup, "y"); } [WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForLocals() { var markup = @"class C { void M() { var x = nameof(T.z.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes2() { var markup = @"class C { void M() { var x = nameof(U.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes3() { var markup = @"class C { void M() { var x = nameof(N.$$) } } namespace N { public class U { public int nope; } } "; await VerifyItemExistsAsync(markup, "U"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes4() { var markup = @" using z = System; class C { void M() { var x = nameof(z.$$) } } "; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings1() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$ "; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings2() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$}""; } }"; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings3() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings4() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings5() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings6() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBeforeFirstStringHole() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBetweenStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task CompletionAfterTypeOfGetType() { await VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives1() { var markup = @" using $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives2() { var markup = @" using N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives3() { var markup = @" using G = $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives4() { var markup = @" using G = N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives5() { var markup = @" using static $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives6() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates1() { var markup = @" using static $$ class A { } delegate void B(); namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates2() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } delegate void D(); namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces1() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } interface I { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces2() { var markup = @" using static $$ class A { } interface I { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods1() { var markup = @" using static A; using static B; static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods2() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods3() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods4() { var markup = @" using static N.A; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods5() { var markup = @" using static N.A; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods6() { var markup = @" using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods7() { var markup = @" using N; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$; } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinSameClassOfferedForCompletion() { var markup = @" public static class Test { static void TestB() { $$ } static void TestA(this string s) { } } "; await VerifyItemExistsAsync(markup, "TestA"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinParentClassOfferedForCompletion() { var markup = @" public static class Parent { static void TestA(this string s) { } static void TestC(string s) { } public static class Test { static void TestB() { $$ } } } "; await VerifyItemExistsAsync(markup, "TestA"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1() { var markup = @" using System; class C { void M(bool x) { try { } catch when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch when $$ "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when $$ "; await VerifyNoItemsExistAsync(markup); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause1() { var markup = @" class C { void M(bool x) { switch (1) { case 1 when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause2() { var markup = @" class C { void M(bool x) { switch (1) { case int i when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionContextCompletionWithinCast() { var markup = @" class Program { void M() { for (int i = 0; i < 5; i++) { var x = ($$) var y = 1; } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInPropertyInitializer() { var markup = @" class A { int abc; int B { get; } = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInPropertyInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInFieldLikeEventInitializer() { var markup = @" class A { Action abc; event Action B = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInFieldLikeEventInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldInitializer() { var markup = @" int aaa = 1; int bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() { var markup = @" Action aaa = null; event Action bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes1() { var markup = @" using A = System class C { A?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes2() { var markup = @" class C { System?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes3() { var markup = @" class C { System.Console?.$$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInIncompletePropertyDeclaration() { var markup = @" class Class1 { public string Property1 { get; set; } } class Class2 { public string Property { get { return this.Source.$$ public Class1 Source { get; set; } }"; await VerifyItemExistsAsync(markup, "Property1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionInShebangComments() { await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script); await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompoundNameTargetTypePreselection() { var markup = @" class Class1 { void goo() { int x = 3; string y = x.$$ } }"; await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer1() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer2() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { 1, $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer1() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer2() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = 1, Y = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElements() { var markup = @" class C { void goo() { var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9); t.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; await VerifyItemExistsAsync(markup, "Alice"); await VerifyItemExistsAsync(markup, "Bob"); await VerifyItemExistsAsync(markup, "CompareTo"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "GetType"); await VerifyItemExistsAsync(markup, "Item2"); await VerifyItemExistsAsync(markup, "ITEM3"); for (var i = 4; i <= 8; i++) { await VerifyItemExistsAsync(markup, "Item" + i); } await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemIsAbsentAsync(markup, "Item1"); await VerifyItemIsAbsentAsync(markup, "Item9"); await VerifyItemIsAbsentAsync(markup, "Rest"); await VerifyItemIsAbsentAsync(markup, "Item3"); } [WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementsCompletionOffMethodGroup() { var markup = @" class C { void goo() { new object().ToString.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; // should not crash await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task NoCompletionInLocalFuncGenericParamList() { var markup = @" class C { void M() { int Local<$$"; await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task CompletionForAwaitWithoutAsync() { var markup = @" class C { void M() { await Local<$$"; await VerifyAnyItemExistsAsync(markup); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel1() { await VerifyItemExistsAsync(@" class C { ($$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel2() { await VerifyItemExistsAsync(@" class C { ($$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel3() { await VerifyItemExistsAsync(@" class C { (C, $$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel4() { await VerifyItemExistsAsync(@" class C { (C, $$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInForeach() { await VerifyItemExistsAsync(@" class C { void M() { foreach ((C, $$ } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInParameterList() { await VerifyItemExistsAsync(@" class C { void M((C, $$) { } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInNameOf() { await VerifyItemExistsAsync(@" class C { void M() { var x = nameof((C, $$ } }", "C"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription() { await VerifyItemExistsAsync(@" class C { void M() { void Local() { } $$ } }", "Local", "void Local()"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription2() { await VerifyItemExistsAsync(@" using System; class C { class var { } void M() { Action<int> Local(string x, ref var @class, params Func<int, string> f) { return () => 0; } $$ } }", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)"); } [WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterDot() { var markup = @"namespace ConsoleApplication253 { class Program { static void Main(string[] args) { M(E.$$) } static void M(E e) { } } enum E { A, B, } } "; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup1() { var markup = @"namespace ConsoleApp { class Program { static void Main(string[] args) { Main.$$ } } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup2() { var markup = @"class C { void M<T>() {M<C>.$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup3() { var markup = @"class C { void M() {M.$$} } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() { var markup = @"public static class Extensions { public static T Get<T>(this object o) => $$} "; await VerifyItemExistsAsync(markup, "o"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task EnumConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Enum"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Delegate"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task MulticastDelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "MulticastDelegate"); } private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString) { var template = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ThenIncludeIntellisenseBug { class Program { static void Main(string[] args) { var registrations = new List<Registration>().AsQueryable(); var reg = registrations.Include(r => r.Activities).ThenInclude([1]); } } internal class Registration { public ICollection<Activity> Activities { get; set; } } public class Activity { public Task Task { get; set; } } public class Task { public string Name { get; set; } } public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity> { } public static class EntityFrameworkQuerybleExtensions { public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>( this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } [2] } }"; return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenInclude() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoExpression() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgument() { var markup = CreateThenIncludeTestCode("0, b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentNoOverlap() { var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath, Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemIsAbsentAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeGenericAndNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<Registration, Activity> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<ICollection<Activity>, Activity> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Activity>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaWithOverloads() { var markup = @" using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ClassLibrary1 { class SomeItem { public string A; public int B; } class SomeCollection<T> : List<T> { public virtual SomeCollection<T> Include(string path) => null; } static class Extensions { public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path) => null; public static IList Include(this IList source, string path) => null; public static IList<T> Include<T>(this IList<T> source, string path) => null; } class Program { void M(SomeCollection<SomeItem> c) { var a = from m in c.Include(t => t.$$); } } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads2() { var markup = @" using System; class C { void M(Action<int> a) { } void M(string s) { } void Test() { M(p => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads3() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M((int p) => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads4() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M(p => p.$$); } }"; await VerifyItemExistsAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParameters() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new List<Product>(), arg => arg.$$); } static void Create<T>(List<T> list, Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1, Product2>(), arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads2() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1,Product2>(),arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } class Product3 { public void MyProperty3() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); await VerifyItemExistsAsync(markup, "MyProperty3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClass() { var markup = @" using System; class Program<T> { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemIsAbsentAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType() { var markup = @" using System; class Program<T> where T : Product { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod() { var markup = @" using System; class Program { static void M() { Create(arg => arg.$$); } static void Create<T>(Action<T> expression) where T : Product { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x = 7, Action<string> y = null) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x, int z, Action<string> y) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() { var markup = @" using System; static class CExtensions { public static void X(this C x, Action<string> y) { } } class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() { var markup = @" using System; public static void X(this C x, Action<string> y) { } public class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithNonFunctionsAsArguments() { var markup = @" using System; class c { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> configure) { var builder = new Builder(); configure(builder); } } class Builder { public int Something { get; set; } }"; await VerifyItemExistsAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAsArguments() { var markup = @" using System; class Program { public delegate void Delegate1(Uri u); public delegate void Delegate2(Guid g); public void M(Delegate1 d) { } public void M(Delegate2 d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Uri await VerifyItemExistsAsync(markup, "AbsoluteUri"); await VerifyItemExistsAsync(markup, "Fragment"); await VerifyItemExistsAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments() { var markup = @" using System; class Program { public delegate void Delegate1<T1,T2>(T2 t2, T1 t1); public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1); public void M(Delegate1<Uri,Guid> d) { } public void M(Delegate2<Uri,Guid> d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Should not appear for Uri await VerifyItemIsAbsentAsync(markup, "AbsoluteUri"); await VerifyItemIsAbsentAsync(markup, "Fragment"); await VerifyItemIsAbsentAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsBeforeParams() { var markup = @" using System; class C { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "AnotherSomething"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "Something"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsInParams() { var markup = @" using System; class C { void M() { Goo(b0 => { }, b1 => {}, b2 => { b2.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "AnotherSomething"); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilterWithExperimentEnabled() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestNoTargetTypeFilterWithExperimentDisabled() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false); var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotOnObjectMembers() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotNamedTypes() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { void M(C c) { M($$); } }"; await VerifyItemExistsAsync( markup, "c", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter }); await VerifyItemExistsAsync( markup, "C", matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() { var markup = @" public static class Ext { public static void DoSomething<T>(this T thing, string s) where T : class, I { } } public interface I { } public class C { public void M(string s) { this.$$ } }"; await VerifyItemExistsAsync(markup, "M"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>"); } [WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionInStaticMethod() { await VerifyItemExistsAsync(@" class C { static void M() { void Local() { } $$ } }", "Local"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")] public async Task NoItemWithEmptyDisplayName() { var markup = @" class C { static void M() { int$$ } } "; await VerifyItemIsAbsentAsync( markup, "", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter }); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar) { var markup = @" class Program { private void Bar() { F$$ } private void Foo(int i) { } private void Foo(int i, int c) { } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(){commitChar} }} private void Foo(int i) {{ }} private void Foo(int i, int c) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithSemicolonInNestedMethod(char commitChar) { var markup = @" class Program { private void Bar() { Foo(F$$); } private int Foo(int i) { return 1; } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(Foo(){commitChar}); }} private int Foo(int i) {{ return 1; }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) { var markup = @" using System; class Program { private void Bar() { Bar2(F$$); } private void Foo() { } void Bar2(Action t) { } }"; var expected = $@" using System; class Program {{ private void Bar() {{ Bar2(Foo{commitChar}); }} private void Foo() {{ }} void Bar2(Action t) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) { var markup = @" class Program { private static void Bar() { var o = new P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = new Program(){commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) { var markup = @" class Program { private static void Bar() { var o = P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = Program{commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) { var markup = @" using String2 = System.String; namespace Bar1 { class Program { private static void Bar() { var o = new S$$ } } }"; var expected = $@" using String2 = System.String; namespace Bar1 {{ class Program {{ private static void Bar() {{ var o = new String2(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionWithSemicolonUnderNameofContext() { var markup = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(B$$) } } }"; var expected = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(Bar;) } } }"; await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';'); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatchWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPropertyPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { public RankedMusicians R; void M(C m) { if (m is { R: RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ChildClassAfterPatternMatch() { var markup = @"namespace N { public class D { public class E { } } class C { void M(object m) { if (m is D.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "E"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpression() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpressionWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() { var markup = @" public class C { [System.Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() { var markup = @" public class C { [System.Obsolete] public void M() { } [System.Obsolete] public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreCustomObsoleteAttribute() { var markup = @" public class ObsoleteAttribute: System.Attribute { } public class C { [Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); } [InlineData("int", "")] [InlineData("int[]", "int a")] [Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList) { // Check the description displayed is based on symbol matches targeted type SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = $@"public class C {{ bool Bar(int a, int b) => false; int Bar() => 0; int[] Bar(int a) => null; bool N({targetType} x) => true; void M(C c) {{ N(c.$$); }} }}"; await VerifyItemExistsAsync( markup, "Bar", expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesNotSuggestedInDeclarationDeconstruction() { await VerifyItemIsAbsentAsync(@" class C { int M() { var (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { int y; (var x, $$) = (0, 0); } }", "y"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")] public async Task TestTypeParameterConstraintedToInterfaceWithStatics() { var source = @" interface I1 { static void M0(); static abstract void M1(); abstract static int P1 { get; set; } abstract static event System.Action E1; } interface I2 { static abstract void M2(); } class Test { void M<T>(T x) where T : I1, I2 { T.$$ } } "; await VerifyItemIsAbsentAsync(source, "M0"); await VerifyItemExistsAsync(source, "M1"); await VerifyItemExistsAsync(source, "M2"); await VerifyItemExistsAsync(source, "P1"); await VerifyItemExistsAsync(source, "E1"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { [UseExportProvider] public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SymbolCompletionProvider); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestExperimentationService)); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFile(SourceCodeKind sourceCodeKind) { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind) { await VerifyItemExistsAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashR() => await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashLoad() => await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirective() { await VerifyItemIsAbsentAsync(@"using $$", @"String"); await VerifyItemIsAbsentAsync(@"using $$ = System", @"System"); await VerifyItemExistsAsync(@"using $$", @"System"); await VerifyItemExistsAsync(@"using T = $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegionWithUsing() { await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegionWithUsing() { await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineXmlComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenCharLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute1() { await VerifyItemExistsAsync(@"[assembly: $$]", @"System"); await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SystemAttributeIsNotAnAttribute() { var content = @"[$$] class CL {}"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeAttribute() { var content = @"[$$] class CL {}"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAttribute() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodAttribute() { var content = @"class CL { [$$] void Method() {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodTypeParamAttribute() { var content = @"class CL{ void Method<[A$$]T> () {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamAttribute() { var content = @"class CL{ void Method ([$$]int i) {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_TopLevel() { var source = @"namespace $$ { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_Nested() { var source = @"; namespace System { namespace $$ { } }"; await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers() { var source = @"using System; namespace $$"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace() { var source = @"using System; namespace $$;"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelWithPeer() { var source = @" namespace A { } namespace $$"; await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithNoPeers() { var source = @" namespace A { namespace $$ }"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithPeer() { var source = @" namespace A { namespace B { } namespace $$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() { var source = @"namespace N$$S"; await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNested() { var source = @" namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace $$ namespace C1 { } } namespace B.C2 { } } namespace A.B.C3 { }"; // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // C1 => A.B.?.C1 // C2 => A.B.B.C2 // C3 => A.A.B.C3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); // Because of the above, B does end up in the completion list // since A.B.B appears to be a peer of the new declaration await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NoPeers() { var source = @"namespace A.$$"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer() { var source = @" namespace A.B { } namespace A.$$"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace() { var source = @" namespace A.B { } namespace A.$$;"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NestedWithPeer() { var source = @" namespace A { namespace B.C { } namespace B.$$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNested() { var source = @" namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem.Runtime { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnKeyword() { var source = @"name$$space System { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnNestedKeyword() { var source = @" namespace System { name$$space Runtime { } }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace C.$$ namespace C.D1 { } } namespace B.C.D2 { } } namespace A.B.C.D3 { }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); // Ideally, all the D* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // D1 => A.B.C.C.?.D1 // D2 => A.B.B.C.D2 // D3 => A.A.B.C.D3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnderNamespace() { await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType1() { await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType2() { var content = @"namespace NS { class CL {} $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideProperty() { var content = @"class C { private string name; public string Name { set { name = $$"; await VerifyItemExistsAsync(content, @"value"); await VerifyItemExistsAsync(content, @"C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDot() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingAlias() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMember() { var content = @"class CL { $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMemberAccessibility() { var content = @"class CL { public $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BadStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameter() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionTypePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StackAllocArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseTypeOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DeclarationStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VariableDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementNoToken() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldDeclaration() { var content = @"class CL { $$ i"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventFieldDeclaration() { var content = @"class CL { event $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclaration() { var content = @"class CL { explicit operator $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclarationNoToken() { var content = @"class CL { explicit $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PropertyDeclaration() { var content = @"class CL { $$ Prop {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventDeclaration() { var content = @"class CL { event $$ Event {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerDeclaration() { var content = @"class CL { $$ this"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter() { var content = @"class CL { void Method($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayType() { var content = @"class CL { $$ ["; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PointerType() { var content = @"class CL { $$ *"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableType() { var content = @"class CL { $$ ?"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateDeclaration() { var content = @"class CL { delegate $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration() { var content = @"class CL { $$ M("; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OperatorDeclaration() { var content = @"class CL { $$ operator"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Argument() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseInPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LetClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OrderingExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SelectClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThrowStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System"); } [WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YieldReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LockStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EqualsValueClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementInitializersPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementConditionOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementIncrementorsPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhileStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayRankSpecifierSizesPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrefixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PostfixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenTruePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenFalsePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseInExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseLeftExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseRightExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhereClauseConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseGroupExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseByExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IfStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchLabelCase() { var content = @"switch(i) { case $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchPatternLabelCase() { var content = @"switch(i) { case $$ when"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionFirstBranch() { var content = @"i switch { $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionSecondBranch() { var content = @"i switch { 1 => true, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternFirstPosition() { var content = @"i is ($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternSecondPosition() { var content = @"i is (1, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternFirstPosition() { var content = @"i is { P: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternSecondPosition() { var content = @"i is { P1: 1, P2: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InitializerExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseList() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseAnotherWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause1() { await VerifyItemExistsAsync(@"class CL<T> where $$", @"T"); await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T"); await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause2() { await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause3() { await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1"); await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseListWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedName() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedNamespace() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedType() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstructorInitializer() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Checked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Unchecked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Locals() => await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameters() => await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AnonymousMethodDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommonTypesInNewExpressionContext() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionForUnboundTypes() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInTypeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInDefault() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInSizeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInGenericParameterList() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterNumericLiteral() { // NOTE: the Completion command handler will suppress this case if the user types '.', // but we still need to show members if the user specifically invokes statement completion here. await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterParenthesizedNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedNumericLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterArithmeticExpression() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals"); [WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceTypesAvailableInUsingAlias() => await VerifyItemExistsAsync(@"using S = System.$$", "String"); [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember1() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember2() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { this.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember3() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { base.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember1() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember2() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { B.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember3() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { A.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedInstanceAndStaticMembers() { var markup = @" class A { private static void HiddenStatic() { } protected static void GooStatic() { } private void HiddenInstance() { } protected void GooInstance() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "HiddenStatic"); await VerifyItemExistsAsync(markup, "GooStatic"); await VerifyItemIsAbsentAsync(markup, "HiddenInstance"); await VerifyItemExistsAsync(markup, "GooInstance"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer1() { var markup = @" class C { void M() { for (int i = 0; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer2() { var markup = @" class C { void M() { for (int i = 0; i < 10; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersInClass() { var markup = @" class C<T, R> { $$ } "; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(ref $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(out $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(in $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(ref String parameter) { M(ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(out String parameter) { M(out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(in String parameter) { M(in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefExpression_TypeAndVariable() { var markup = @" using System; class C { void M(String parameter) { ref var x = ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref readonly $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType1() { var markup = @" class Q { $$ class R { } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType2() { var markup = @" class Q { class R { $$ } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType3() { var markup = @" class Q { class R { } $$ } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Regular() { var markup = @" class Q { class R { } } $$"; // At EOF // Top-level statements are not allowed to follow classes, but we still offer it in completion for a few // reasons: // // 1. The code is simpler // 2. It's a relatively rare coding practice to define types outside of namespaces // 3. It allows the compiler to produce a better error message when users type things in the wrong order await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Script() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType5() { var markup = @" class Q { class R { } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType6() { var markup = @" class Q { class R { $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenTypeAndLocal() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void goo() { int i = 5; i.$$ List<string> ml = new List<string>(); } }"; await VerifyItemExistsAsync(markup, "CompareTo"); } [WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { AwaitTest test = new AwaitTest(); test.Test1().Wait(); } } class AwaitTest { List<string> stringList = new List<string>(); public async Task<bool> Test1() { stringList.$$ await Test2(); return true; } public async Task<bool> Test2() { return true; } }"; await VerifyItemExistsAsync(markup, "Add"); } [WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterNewInScript() { var markup = @" using System; new $$"; await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodsInScript() { var markup = @" using System.Linq; var a = new int[] { 1, 2 }; a.$$"; await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionsInForLoopInitializer() { var markup = @" public class C { public void M() { int count = 0; for ($$ "; await VerifyItemExistsAsync(markup, "count"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression1() { var markup = @" public class C { public void M() { System.Func<int, int> f = arg => { arg = 2; return arg; }.$$ } } "; await VerifyItemIsAbsentAsync(markup, "ToString"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression2() { var markup = @" public class C { public void M() { ((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$ } } "; await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemExistsAsync(markup, "Invoke"); } [WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InMultiLineCommentAtEndOfFile() { var markup = @" using System; /*$$"; await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersAtEndOfFile() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Outer<T> { class Inner<U> { static void F(T t, U u) { return; } public static void F(T t) { Outer<$$"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForCase() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "case 0:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "default:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchPresentForDefault() { var markup = @" class Program { static void Main() { int x; switch (x) { default: goto $$"; await VerifyItemExistsAsync(markup, "default"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto1() { var markup = @" class Program { static void Main() { Goo: int Goo; goto $$"; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto2() { var markup = @" class Program { static void Main() { Goo: int Goo; goto Goo $$"; await VerifyItemIsAbsentAsync(markup, "Goo"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeName() { var markup = @" using System; [$$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifier() { var markup = @" using System; [assembly:$$ "; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeList() { var markup = @" using System; [CLSCompliant, $$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameBeforeClass() { var markup = @" using System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifierBeforeClass() { var markup = @" using System; [assembly:$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeArgumentList() { var markup = @" using System; [CLSCompliant($$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInsideClass() { var markup = @" using System; class C { $$ }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName1() { var markup = @" using Alias = System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName2() { var markup = @" using Alias = Goo; namespace Goo { } [$$ class C { }"; await VerifyItemIsAbsentAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName3() { var markup = @" using Alias = Goo; namespace Goo { class A : System.Attribute { } } [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace() { var markup = @" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace2() { var markup = @" namespace Test { namespace Two { class MyAttribute : System.Attribute { } [Test.Two.$$ class Program { } } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task KeywordsUsedAsLocals() { var markup = @" class C { void M() { var error = 0; var method = 0; var @int = 0; Console.Write($$ } }"; // preprocessor keyword await VerifyItemExistsAsync(markup, "error"); await VerifyItemIsAbsentAsync(markup, "@error"); // contextual keyword await VerifyItemExistsAsync(markup, "method"); await VerifyItemIsAbsentAsync(markup, "@method"); // full keyword await VerifyItemExistsAsync(markup, "@int"); await VerifyItemIsAbsentAsync(markup, "int"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords1() { var markup = @" class C { void M() { var from = new[]{1,2,3}; var r = from x in $$ } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords2() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where $$ == @where.Length select @from; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords3() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where @from == @where.Length select $$; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAlias() { var markup = @" class MyAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() { var markup = @" class namespaceAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute1() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute2() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace2"); await VerifyItemExistsAsync(markup, "Namespace3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute3() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.$$]"; await VerifyItemExistsAsync(markup, "Namespace4"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute4() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.Namespace4.$$]"; await VerifyItemExistsAsync(markup, "Custom"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() { var markup = @" using Namespace1Alias = Namespace1; using Namespace2Alias = Namespace1.Namespace2; using Namespace3Alias = Namespace1.Namespace3; using Namespace4Alias = Namespace1.Namespace3.Namespace4; namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1Alias"); await VerifyItemIsAbsentAsync(markup, "Namespace2Alias"); await VerifyItemExistsAsync(markup, "Namespace3Alias"); await VerifyItemExistsAsync(markup, "Namespace4Alias"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithoutNestedAttribute() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } } } [$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace1"); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariableInQuerySelect() { var markup = @" using System.Linq; class P { void M() { var src = new string[] { ""Goo"", ""Bar"" }; var q = from x in src select x.$$"; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsPatternExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ 1"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchPatternCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$ when"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchGotoCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case MAX_SIZE: break; case GOO: goto case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInEnumMember() { var markup = @" class C { public const int GOO = 0; enum E { A = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute1() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage($$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute2() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(GOO, $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute3() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(validOn: $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute4() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(AllowMultiple = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInParameterDefaultValue() { var markup = @" class C { public const int GOO = 0; void M(int x = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstField() { var markup = @" class C { public const int GOO = 0; const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstLocal() { var markup = @" class C { public const int GOO = 0; void M() { const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1Overload() { var markup = @" class C { void M(int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2Overloads() { var markup = @" class C { void M(int i) { } void M(out int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1GenericOverload() { var markup = @" class C { void M<T>(T i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2GenericOverloads() { var markup = @" class C { void M<T>(int i) { } void M<T>(out int i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionNamedGenericType() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionParameter() { var markup = @" class C<T> { void M(T goo) { $$"; await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionGenericTypeParameter() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionAnonymousType() { var markup = @" class C { void M() { var a = new { }; $$ "; var expectedDescription = $@"({FeaturesResources.local_variable}) 'a a {FeaturesResources.Anonymous_Types_colon} 'a {FeaturesResources.is_} new {{ }}"; await VerifyItemExistsAsync(markup, "a", expectedDescription); } [WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterNewInAnonymousType() { var markup = @" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } "; await VerifyItemExistsAsync(markup, "Program"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticMethod() { var markup = @" class C { int x = 0; static void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticFieldInitializer() { var markup = @" class C { int x = 0; static int y = $$ } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticMethod() { var markup = @" class C { static int x = 0; static void M() { $$ } } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticFieldInitializer() { var markup = @" class C { static int x = 0; static int y = $$ } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { int i; class inner { void M() { $$ } } } "; await VerifyItemIsAbsentAsync(markup, "i"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { static int i; class inner { void M() { $$ } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyEnumMembersInEnumMemberAccess() { var markup = @" class C { enum x {a,b,c} void M() { x.$$ } } "; await VerifyItemExistsAsync(markup, "a"); await VerifyItemExistsAsync(markup, "b"); await VerifyItemExistsAsync(markup, "c"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoEnumMembersInEnumLocalAccess() { var markup = @" class C { enum x {a,b,c} void M() { var y = x.a; y.$$ } } "; await VerifyItemIsAbsentAsync(markup, "a"); await VerifyItemIsAbsentAsync(markup, "b"); await VerifyItemIsAbsentAsync(markup, "c"); await VerifyItemExistsAsync(markup, "Equals"); } [WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaParameterDot() { var markup = @" using System; using System.Linq; class A { public event Func<String, String> E; } class Program { static void Main(string[] args) { new A().E += ss => ss.$$ } } "; await VerifyItemExistsAsync(markup, "Substring"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAtRoot_Interactive() { await VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterClass_Interactive() { await VerifyItemIsAbsentAsync( @"class C { } $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalStatement_Interactive() { await VerifyItemIsAbsentAsync( @"System.Console.WriteLine(); $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() { await VerifyItemIsAbsentAsync( @"int i = 0; $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInUsingAlias() { await VerifyItemIsAbsentAsync( @"using Goo = $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInEmptyStatement() { await VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideSetter() { await VerifyItemExistsAsync( @"class C { int Goo { set { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideAdder() { await VerifyItemExistsAsync( @"class C { event int Goo { add { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideRemover() { await VerifyItemExistsAsync( @"class C { event int Goo { remove { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterDot() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { this.$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterArrow() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a->$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterColonColon() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a::$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInGetter() { await VerifyItemIsAbsentAsync( @"class C { int Goo { get { $$", "value"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterNullableTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkAndPartialIdentifierInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskAndPartialIdentifierInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* f$$", "goo"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterEventFieldDeclaredInSameType() { await VerifyItemExistsAsync( @"class C { public event System.EventHandler E; void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterFullEventDeclaredInSameType() { await VerifyItemIsAbsentAsync( @"class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterEventDeclaredInDifferentType() { await VerifyItemIsAbsentAsync( @"class C { void M() { System.Console.CancelKeyPress.$$", "Invoke"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotInObjectInitializerMemberContext() { await VerifyItemIsAbsentAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$", "x"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task AfterPointerMemberAccess() { await VerifyItemExistsAsync(@" struct MyStruct { public int MyField; } class Program { static unsafe void Main(string[] args) { MyStruct s = new MyStruct(); MyStruct* ptr = &s; ptr->$$ }}", "MyField"); } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. [WorkItem(11931, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task VerbatimAttributes() { var code = @" using System; public class X : Attribute { } public class XAttribute : Attribute { } [@X$$] class Class3 { } "; await VerifyItemExistsAsync(code, "X"); await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute")); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; $$ } } ", "Console"); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for ($$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclaration() { // "int goo = goo = 1" is a legal declaration await VerifyItemExistsAsync(@" class Program { void M() { int goo = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclarator() { // "int bar = bar = 1" is legal in a declarator await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$, int baz = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclaration() { await VerifyItemIsAbsentAsync(@" class Program { void M() { $$ int goo = 0; } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclarator() { await VerifyItemIsAbsentAsync(@" class Program { void M() { int goo = $$, bar = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAfterDeclarator() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAsOutArgumentInInitializerExpression() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = Bar(out $$ } int Bar(out int x) { x = 3; return 5; } }", "goo"); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverriddenSymbolsFilteredFromCompletionList() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" public class B { public virtual void Goo(int original) { } } public class D : B { public override void Goo(int derived) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { C c = new C(); c.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Goo() { } } public class D : B { public void Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { $$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")] [WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")] [WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { public int Bar { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateNever() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAlways() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads1() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads2() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateNever() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAlways() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateNever() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAlways() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" public class Goo : Bar { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Bar { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAlways() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAdvanced() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Always() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Never() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 0, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestColorColor1() { var markup = @" class A { static void Goo() { } void Bar() { } static void Main() { A A = new A(); A.$$ } }"; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType1() { var markup = @" using System; class C { public static void Main() { $$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType2() { var markup = @" using System; class C { public static void Main() { C$$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "IndexProp", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } [WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDeclarationAmbiguity() { var markup = @" using System; class Program { void Main() { Environment.$$ var v; } }"; await VerifyItemExistsAsync(markup, "CommandLine"); } [WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldDeclarationAmbiguity() { var markup = @" using System; Environment.$$ var v; }"; await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCursorOnClassCloseBrace() { var markup = @" using System; class Outer { class Inner { } $$}"; await VerifyItemExistsAsync(markup, "Inner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync1() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync2() { var markup = @" using System.Threading.Tasks; class Program { public async T$$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterAsyncInMethodBody() { var markup = @" using System.Threading.Tasks; class Program { void goo() { var x = async $$ } }"; await VerifyItemIsAbsentAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable1() { var markup = @" class Program { void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable2() { var markup = @" class Program { async void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable1() { var markup = @" using System.Threading; using System.Threading.Tasks; class Program { async Task goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable2() { var markup = @" using System.Threading.Tasks; class Program { async Task<int> goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpression() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = await request.$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; // Nothing should be found: no awaiter for request. await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Task<Request>(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { $$ } }"; await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); } [WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersOnDottingIntoUnboundType() { var markup = @" class Program { RegistryKey goo; static void Main(string[] args) { goo.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeArgumentsInConstraintAfterBaselist() { var markup = @" public class Goo<T> : System.Object where $$ { }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDestructor() { var markup = @" class C { ~C() { $$ "; await VerifyItemIsAbsentAsync(markup, "Finalize"); } [WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodOnCovariantInterface() { var markup = @" class Schema<T> { } interface ISet<out T> { } static class SetMethods { public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { } } class Context { public ISet<T> Set<T>() { return null; } } class CustomSchema : Schema<int> { } class Program { static void Main(string[] args) { var set = new Context().Set<CustomSchema>(); set.$$ "; await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachInsideParentheses() { var markup = @" using System; class C { void M() { foreach($$) "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldInitializerInP2P() { var markup = @" class Class { int i = Consts.$$; }"; var referencedCode = @" public static class Consts { public const int C = 1; }"; await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false); } [WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowWithEqualsSign() { var markup = @" class c { public int value {set; get; }} class d { void goo() { c goo = new c { value$$= } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterThisDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { this.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { base.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInScriptContext() => await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); [WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoNestedTypeWhenDisplayingInstance() { var markup = @" class C { class D { } void M2() { new C().$$ } }"; await VerifyItemIsAbsentAsync(markup, "D"); } [WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchVariableInExceptionFilter() { var markup = @" class C { void M() { try { } catch (System.Exception myExn) when ($$"; await VerifyItemExistsAsync(markup, "myExn"); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterExternAlias() { var markup = @" class C { void goo() { global::$$ } }"; await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExternAliasSuggested() { var markup = @" extern alias Bar; class C { void goo() { $$ } }"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassDestructor() { var markup = @" class C { class N { ~$$ } }"; await VerifyItemExistsAsync(markup, "N"); await VerifyItemIsAbsentAsync(markup, "C"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TildeOutsideClass() { var markup = @" class C { class N { } } ~$$"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "N"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StructDestructor() { var markup = @" struct C { ~$$ }"; await VerifyItemIsAbsentAsync(markup, "C"); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("record")] [InlineData("record class")] public async Task RecordDestructor(string record) { var markup = $@" {record} C {{ ~$$ }}"; await VerifyItemExistsAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RecordStructDestructor() { var markup = $@" record struct C {{ ~$$ }}"; await VerifyItemIsAbsentAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { int x; void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { $$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR class G { public void DoGStuff() {} } #endif void goo() { new G().$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { int xyz; $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { #if PROJ1 int xyz; #endif $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { LABEL: int xyz; goto $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.label}) LABEL"; await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] { 1, 2, 3 } select $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); } [WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void Shared() { var x = GetThing(); x.$$ } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE public int x; #endif #if TWO public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({ FeaturesResources.field }) int C.x"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if TWO public int x; #endif #if ONE public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = "int C.x { get; set; }"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessWalkUp() { var markup = @" public class B { public A BA; public B BB; } class A { public A AA; public A AB; public int? x; public void goo() { A a = null; var q = a?.$$AB.BA.AB.BA; } }"; await VerifyItemExistsAsync(markup, "AA"); await VerifyItemExistsAsync(markup, "AB"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { A a = null; var q = a?.s?.$$; } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped2() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { var q = s?.$$i?.ToString(); } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt?.$$ } } "; await VerifyItemExistsAsync(markup, "Day"); await VerifyItemIsAbsentAsync(markup, "Value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableIsNotUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt.$$ } } "; await VerifyItemExistsAsync(markup, "Value"); await VerifyItemIsAbsentAsync(markup, "Day"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterConditionalIndexing() { var markup = @" public struct S { public int? i; } class A { public S[] s; public void goo() { A a = null; var q = a?.s?[$$; } }"; await VerifyItemExistsAsync(markup, "System"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses1() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.$$b?.c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses2() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.$$c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "c"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses3() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.c?.$$d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "d"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnSelf() { var markup = @"using System; [My] class X { [My$$] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnOuterType() { var markup = @"using System; [My] class Y { } [$$] class X { [My] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType() { var markup = @"abstract class Test { private int _field; public sealed class InnerTest : Test { public void SomeTest() { $$ } } }"; await VerifyItemExistsAsync(markup, "_field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType2() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { $$ // M recommended and accessible } class NN { void Test2() { // M inaccessible and not recommended } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType3() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN { void Test2() { $$ // M inaccessible and not recommended } } } }"; await VerifyItemIsAbsentAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType4() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN : N { void Test2() { $$ // M accessible and recommended. } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType5() { var markup = @" class D { public void Q() { } } class C<T> : D { class N { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "Q"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType6() { var markup = @" class Base<T> { public int X; } class Derived : Base<int> { class Nested { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "X"); } [WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoTypeParametersDefinedInCrefs() { var markup = @"using System; /// <see cref=""Program{T$$}""/> class Program<T> { }"; await VerifyItemIsAbsentAsync(markup, "T"); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList1() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList2() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<string,$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionInAliasedType() { var markup = @" using IAlias = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C { I$$ } "; await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinNameOf() { var markup = @" class C { void goo() { var x = nameof($$) } } "; await VerifyAnyItemExistsAsync(markup); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y1"); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y2"); } [WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteDeclarationExpressionType() { var markup = @" using System; class C { void goo() { var x = Console.$$ var y = 3; } } "; await VerifyItemExistsAsync(markup, "WriteLine"); } [WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticAndInstanceInNameOf() { var markup = @" using System; class C { class D { public int x; public static int y; } void goo() { var z = nameof(C.D.$$ } } "; await VerifyItemExistsAsync(markup, "x"); await VerifyItemExistsAsync(markup, "y"); } [WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForLocals() { var markup = @"class C { void M() { var x = nameof(T.z.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes2() { var markup = @"class C { void M() { var x = nameof(U.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes3() { var markup = @"class C { void M() { var x = nameof(N.$$) } } namespace N { public class U { public int nope; } } "; await VerifyItemExistsAsync(markup, "U"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes4() { var markup = @" using z = System; class C { void M() { var x = nameof(z.$$) } } "; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings1() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$ "; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings2() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$}""; } }"; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings3() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings4() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings5() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings6() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBeforeFirstStringHole() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBetweenStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task CompletionAfterTypeOfGetType() { await VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives1() { var markup = @" using $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives2() { var markup = @" using N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives3() { var markup = @" using G = $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives4() { var markup = @" using G = N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives5() { var markup = @" using static $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives6() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates1() { var markup = @" using static $$ class A { } delegate void B(); namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates2() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } delegate void D(); namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces1() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } interface I { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces2() { var markup = @" using static $$ class A { } interface I { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods1() { var markup = @" using static A; using static B; static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods2() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods3() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods4() { var markup = @" using static N.A; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods5() { var markup = @" using static N.A; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods6() { var markup = @" using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods7() { var markup = @" using N; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$; } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinSameClassOfferedForCompletion() { var markup = @" public static class Test { static void TestB() { $$ } static void TestA(this string s) { } } "; await VerifyItemExistsAsync(markup, "TestA"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinParentClassOfferedForCompletion() { var markup = @" public static class Parent { static void TestA(this string s) { } static void TestC(string s) { } public static class Test { static void TestB() { $$ } } } "; await VerifyItemExistsAsync(markup, "TestA"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1() { var markup = @" using System; class C { void M(bool x) { try { } catch when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch when $$ "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when $$ "; await VerifyNoItemsExistAsync(markup); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause1() { var markup = @" class C { void M(bool x) { switch (1) { case 1 when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause2() { var markup = @" class C { void M(bool x) { switch (1) { case int i when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionContextCompletionWithinCast() { var markup = @" class Program { void M() { for (int i = 0; i < 5; i++) { var x = ($$) var y = 1; } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInPropertyInitializer() { var markup = @" class A { int abc; int B { get; } = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInPropertyInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInFieldLikeEventInitializer() { var markup = @" class A { Action abc; event Action B = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInFieldLikeEventInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldInitializer() { var markup = @" int aaa = 1; int bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() { var markup = @" Action aaa = null; event Action bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes1() { var markup = @" using A = System class C { A?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes2() { var markup = @" class C { System?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes3() { var markup = @" class C { System.Console?.$$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInIncompletePropertyDeclaration() { var markup = @" class Class1 { public string Property1 { get; set; } } class Class2 { public string Property { get { return this.Source.$$ public Class1 Source { get; set; } }"; await VerifyItemExistsAsync(markup, "Property1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionInShebangComments() { await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script); await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompoundNameTargetTypePreselection() { var markup = @" class Class1 { void goo() { int x = 3; string y = x.$$ } }"; await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer1() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer2() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { 1, $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer1() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer2() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = 1, Y = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElements() { var markup = @" class C { void goo() { var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9); t.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; await VerifyItemExistsAsync(markup, "Alice"); await VerifyItemExistsAsync(markup, "Bob"); await VerifyItemExistsAsync(markup, "CompareTo"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "GetType"); await VerifyItemExistsAsync(markup, "Item2"); await VerifyItemExistsAsync(markup, "ITEM3"); for (var i = 4; i <= 8; i++) { await VerifyItemExistsAsync(markup, "Item" + i); } await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemIsAbsentAsync(markup, "Item1"); await VerifyItemIsAbsentAsync(markup, "Item9"); await VerifyItemIsAbsentAsync(markup, "Rest"); await VerifyItemIsAbsentAsync(markup, "Item3"); } [WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementsCompletionOffMethodGroup() { var markup = @" class C { void goo() { new object().ToString.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; // should not crash await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task NoCompletionInLocalFuncGenericParamList() { var markup = @" class C { void M() { int Local<$$"; await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task CompletionForAwaitWithoutAsync() { var markup = @" class C { void M() { await Local<$$"; await VerifyAnyItemExistsAsync(markup); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel1() { await VerifyItemExistsAsync(@" class C { ($$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel2() { await VerifyItemExistsAsync(@" class C { ($$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel3() { await VerifyItemExistsAsync(@" class C { (C, $$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel4() { await VerifyItemExistsAsync(@" class C { (C, $$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInForeach() { await VerifyItemExistsAsync(@" class C { void M() { foreach ((C, $$ } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInParameterList() { await VerifyItemExistsAsync(@" class C { void M((C, $$) { } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInNameOf() { await VerifyItemExistsAsync(@" class C { void M() { var x = nameof((C, $$ } }", "C"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription() { await VerifyItemExistsAsync(@" class C { void M() { void Local() { } $$ } }", "Local", "void Local()"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription2() { await VerifyItemExistsAsync(@" using System; class C { class var { } void M() { Action<int> Local(string x, ref var @class, params Func<int, string> f) { return () => 0; } $$ } }", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)"); } [WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterDot() { var markup = @"namespace ConsoleApplication253 { class Program { static void Main(string[] args) { M(E.$$) } static void M(E e) { } } enum E { A, B, } } "; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup1() { var markup = @"namespace ConsoleApp { class Program { static void Main(string[] args) { Main.$$ } } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup2() { var markup = @"class C { void M<T>() {M<C>.$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup3() { var markup = @"class C { void M() {M.$$} } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() { var markup = @"public static class Extensions { public static T Get<T>(this object o) => $$} "; await VerifyItemExistsAsync(markup, "o"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task EnumConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Enum"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Delegate"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task MulticastDelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "MulticastDelegate"); } private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString) { var template = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ThenIncludeIntellisenseBug { class Program { static void Main(string[] args) { var registrations = new List<Registration>().AsQueryable(); var reg = registrations.Include(r => r.Activities).ThenInclude([1]); } } internal class Registration { public ICollection<Activity> Activities { get; set; } } public class Activity { public Task Task { get; set; } } public class Task { public string Name { get; set; } } public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity> { } public static class EntityFrameworkQuerybleExtensions { public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>( this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } [2] } }"; return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenInclude() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoExpression() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgument() { var markup = CreateThenIncludeTestCode("0, b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentNoOverlap() { var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath, Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemIsAbsentAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeGenericAndNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<Registration, Activity> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<ICollection<Activity>, Activity> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Activity>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaWithOverloads() { var markup = @" using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ClassLibrary1 { class SomeItem { public string A; public int B; } class SomeCollection<T> : List<T> { public virtual SomeCollection<T> Include(string path) => null; } static class Extensions { public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path) => null; public static IList Include(this IList source, string path) => null; public static IList<T> Include<T>(this IList<T> source, string path) => null; } class Program { void M(SomeCollection<SomeItem> c) { var a = from m in c.Include(t => t.$$); } } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads2() { var markup = @" using System; class C { void M(Action<int> a) { } void M(string s) { } void Test() { M(p => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads3() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M((int p) => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads4() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M(p => p.$$); } }"; await VerifyItemExistsAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParameters() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new List<Product>(), arg => arg.$$); } static void Create<T>(List<T> list, Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1, Product2>(), arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads2() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1,Product2>(),arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } class Product3 { public void MyProperty3() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); await VerifyItemExistsAsync(markup, "MyProperty3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClass() { var markup = @" using System; class Program<T> { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemIsAbsentAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType() { var markup = @" using System; class Program<T> where T : Product { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod() { var markup = @" using System; class Program { static void M() { Create(arg => arg.$$); } static void Create<T>(Action<T> expression) where T : Product { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x = 7, Action<string> y = null) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x, int z, Action<string> y) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() { var markup = @" using System; static class CExtensions { public static void X(this C x, Action<string> y) { } } class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() { var markup = @" using System; public static void X(this C x, Action<string> y) { } public class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithNonFunctionsAsArguments() { var markup = @" using System; class c { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> configure) { var builder = new Builder(); configure(builder); } } class Builder { public int Something { get; set; } }"; await VerifyItemExistsAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAsArguments() { var markup = @" using System; class Program { public delegate void Delegate1(Uri u); public delegate void Delegate2(Guid g); public void M(Delegate1 d) { } public void M(Delegate2 d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Uri await VerifyItemExistsAsync(markup, "AbsoluteUri"); await VerifyItemExistsAsync(markup, "Fragment"); await VerifyItemExistsAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments() { var markup = @" using System; class Program { public delegate void Delegate1<T1,T2>(T2 t2, T1 t1); public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1); public void M(Delegate1<Uri,Guid> d) { } public void M(Delegate2<Uri,Guid> d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Should not appear for Uri await VerifyItemIsAbsentAsync(markup, "AbsoluteUri"); await VerifyItemIsAbsentAsync(markup, "Fragment"); await VerifyItemIsAbsentAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsBeforeParams() { var markup = @" using System; class C { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "AnotherSomething"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "Something"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsInParams() { var markup = @" using System; class C { void M() { Goo(b0 => { }, b1 => {}, b2 => { b2.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "AnotherSomething"); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilterWithExperimentEnabled() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestNoTargetTypeFilterWithExperimentDisabled() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false); var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotOnObjectMembers() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotNamedTypes() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = @"public class C { void M(C c) { M($$); } }"; await VerifyItemExistsAsync( markup, "c", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter }); await VerifyItemExistsAsync( markup, "C", matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() { var markup = @" public static class Ext { public static void DoSomething<T>(this T thing, string s) where T : class, I { } } public interface I { } public class C { public void M(string s) { this.$$ } }"; await VerifyItemExistsAsync(markup, "M"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>"); } [WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionInStaticMethod() { await VerifyItemExistsAsync(@" class C { static void M() { void Local() { } $$ } }", "Local"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")] public async Task NoItemWithEmptyDisplayName() { var markup = @" class C { static void M() { int$$ } } "; await VerifyItemIsAbsentAsync( markup, "", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter }); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar) { var markup = @" class Program { private void Bar() { F$$ } private void Foo(int i) { } private void Foo(int i, int c) { } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(){commitChar} }} private void Foo(int i) {{ }} private void Foo(int i, int c) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithSemicolonInNestedMethod(char commitChar) { var markup = @" class Program { private void Bar() { Foo(F$$); } private int Foo(int i) { return 1; } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(Foo(){commitChar}); }} private int Foo(int i) {{ return 1; }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) { var markup = @" using System; class Program { private void Bar() { Bar2(F$$); } private void Foo() { } void Bar2(Action t) { } }"; var expected = $@" using System; class Program {{ private void Bar() {{ Bar2(Foo{commitChar}); }} private void Foo() {{ }} void Bar2(Action t) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) { var markup = @" class Program { private static void Bar() { var o = new P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = new Program(){commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) { var markup = @" class Program { private static void Bar() { var o = P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = Program{commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) { var markup = @" using String2 = System.String; namespace Bar1 { class Program { private static void Bar() { var o = new S$$ } } }"; var expected = $@" using String2 = System.String; namespace Bar1 {{ class Program {{ private static void Bar() {{ var o = new String2(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionWithSemicolonUnderNameofContext() { var markup = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(B$$) } } }"; var expected = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(Bar;) } } }"; await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';'); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatchWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPropertyPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { public RankedMusicians R; void M(C m) { if (m is { R: RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ChildClassAfterPatternMatch() { var markup = @"namespace N { public class D { public class E { } } class C { void M(object m) { if (m is D.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "E"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpression() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpressionWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() { var markup = @" public class C { [System.Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() { var markup = @" public class C { [System.Obsolete] public void M() { } [System.Obsolete] public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreCustomObsoleteAttribute() { var markup = @" public class ObsoleteAttribute: System.Attribute { } public class C { [Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); } [InlineData("int", "")] [InlineData("int[]", "int a")] [Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList) { // Check the description displayed is based on symbol matches targeted type SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true); var markup = $@"public class C {{ bool Bar(int a, int b) => false; int Bar() => 0; int[] Bar(int a) => null; bool N({targetType} x) => true; void M(C c) {{ N(c.$$); }} }}"; await VerifyItemExistsAsync( markup, "Bar", expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesNotSuggestedInDeclarationDeconstruction() { await VerifyItemIsAbsentAsync(@" class C { int M() { var (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { int y; (var x, $$) = (0, 0); } }", "y"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")] public async Task TestTypeParameterConstraintedToInterfaceWithStatics() { var source = @" interface I1 { static void M0(); static abstract void M1(); abstract static int P1 { get; set; } abstract static event System.Action E1; } interface I2 { static abstract void M2(); } class Test { void M<T>(T x) where T : I1, I2 { T.$$ } } "; await VerifyItemIsAbsentAsync(source, "M0"); await VerifyItemExistsAsync(source, "M1"); await VerifyItemExistsAsync(source, "M2"); await VerifyItemExistsAsync(source, "P1"); await VerifyItemExistsAsync(source, "E1"); } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Classification/ClassificationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Classification { internal static class ClassificationHelpers { private const string FromKeyword = "from"; private const string VarKeyword = "var"; private const string UnmanagedKeyword = "unmanaged"; private const string NotNullKeyword = "notnull"; private const string DynamicKeyword = "dynamic"; private const string AwaitKeyword = "await"; /// <summary> /// Determine the classification type for a given token. /// </summary> /// <param name="token">The token.</param> /// <returns>The correct syntactic classification for the token.</returns> public static string? GetClassification(SyntaxToken token) { if (IsControlKeyword(token)) { return ClassificationTypeNames.ControlKeyword; } else if (SyntaxFacts.IsKeywordKind(token.Kind()) || token.IsKind(SyntaxKind.DiscardDesignation)) { // When classifying `_`, IsKeywordKind handles UnderscoreToken, but need to additional check for DiscardDesignation return ClassificationTypeNames.Keyword; } else if (SyntaxFacts.IsPunctuation(token.Kind())) { return GetClassificationForPunctuation(token); } else if (token.Kind() == SyntaxKind.IdentifierToken) { return GetClassificationForIdentifier(token); } else if (IsStringToken(token)) { return IsVerbatimStringToken(token) ? ClassificationTypeNames.VerbatimStringLiteral : ClassificationTypeNames.StringLiteral; } else if (token.Kind() == SyntaxKind.NumericLiteralToken) { return ClassificationTypeNames.NumericLiteral; } return null; } private static bool IsControlKeyword(SyntaxToken token) { if (token.Parent is null || !IsControlKeywordKind(token.Kind())) { return false; } return IsControlStatementKind(token.Parent.Kind()); } private static bool IsControlKeywordKind(SyntaxKind kind) { switch (kind) { case SyntaxKind.IfKeyword: case SyntaxKind.ElseKeyword: case SyntaxKind.WhileKeyword: case SyntaxKind.ForKeyword: case SyntaxKind.ForEachKeyword: case SyntaxKind.DoKeyword: case SyntaxKind.SwitchKeyword: case SyntaxKind.CaseKeyword: case SyntaxKind.TryKeyword: case SyntaxKind.CatchKeyword: case SyntaxKind.FinallyKeyword: case SyntaxKind.GotoKeyword: case SyntaxKind.BreakKeyword: case SyntaxKind.ContinueKeyword: case SyntaxKind.ReturnKeyword: case SyntaxKind.ThrowKeyword: case SyntaxKind.YieldKeyword: case SyntaxKind.DefaultKeyword: // Include DefaultKeyword as it can be part of a DefaultSwitchLabel case SyntaxKind.InKeyword: // Include InKeyword as it can be part of an ForEachStatement case SyntaxKind.WhenKeyword: // Include WhenKeyword as it can be part of a CatchFilterClause or a pattern WhenClause return true; default: return false; } } private static bool IsControlStatementKind(SyntaxKind kind) { switch (kind) { // Jump Statements case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.YieldBreakStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // Checked Statements case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.SwitchStatement: case SyntaxKind.SwitchSection: case SyntaxKind.CaseSwitchLabel: case SyntaxKind.CasePatternSwitchLabel: case SyntaxKind.DefaultSwitchLabel: case SyntaxKind.TryStatement: case SyntaxKind.CatchClause: case SyntaxKind.CatchFilterClause: case SyntaxKind.FinallyClause: case SyntaxKind.SwitchExpression: case SyntaxKind.ThrowExpression: case SyntaxKind.WhenClause: return true; default: return false; } } private static bool IsStringToken(SyntaxToken token) { return token.IsKind(SyntaxKind.StringLiteralToken) || token.IsKind(SyntaxKind.CharacterLiteralToken) || token.IsKind(SyntaxKind.InterpolatedStringStartToken) || token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken) || token.IsKind(SyntaxKind.InterpolatedStringTextToken) || token.IsKind(SyntaxKind.InterpolatedStringEndToken); } private static bool IsVerbatimStringToken(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { return true; } switch (token.Kind()) { case SyntaxKind.InterpolatedVerbatimStringStartToken: return true; case SyntaxKind.InterpolatedStringStartToken: return false; case SyntaxKind.InterpolatedStringEndToken: { return token.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } case SyntaxKind.InterpolatedStringTextToken: { if (!(token.Parent is InterpolatedStringTextSyntax interpolatedStringText)) { return false; } return interpolatedStringText.Parent is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } } return false; } private static string? GetClassificationForIdentifier(SyntaxToken token) { if (token.Parent is BaseTypeDeclarationSyntax typeDeclaration && typeDeclaration.Identifier == token) { return GetClassificationForTypeDeclarationIdentifier(token); } else if (token.Parent.IsKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl) && delegateDecl.Identifier == token) { return ClassificationTypeNames.DelegateName; } else if (token.Parent.IsKind(SyntaxKind.TypeParameter, out TypeParameterSyntax? typeParameter) && typeParameter.Identifier == token) { return ClassificationTypeNames.TypeParameterName; } else if (token.Parent is MethodDeclarationSyntax methodDeclaration && methodDeclaration.Identifier == token) { return IsExtensionMethod(methodDeclaration) ? ClassificationTypeNames.ExtensionMethodName : ClassificationTypeNames.MethodName; } else if (token.Parent is ConstructorDeclarationSyntax constructorDeclaration && constructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(constructorDeclaration.Parent!); } else if (token.Parent is DestructorDeclarationSyntax destructorDeclaration && destructorDeclaration.Identifier == token) { return GetClassificationTypeForConstructorOrDestructorParent(destructorDeclaration.Parent!); } else if (token.Parent is LocalFunctionStatementSyntax localFunctionStatement && localFunctionStatement.Identifier == token) { return ClassificationTypeNames.MethodName; } else if (token.Parent is PropertyDeclarationSyntax propertyDeclaration && propertyDeclaration.Identifier == token) { return ClassificationTypeNames.PropertyName; } else if (token.Parent is EnumMemberDeclarationSyntax enumMemberDeclaration && enumMemberDeclaration.Identifier == token) { return ClassificationTypeNames.EnumMemberName; } else if (token.Parent is CatchDeclarationSyntax catchDeclaration && catchDeclaration.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is VariableDeclaratorSyntax variableDeclarator && variableDeclarator.Identifier == token) { var varDecl = variableDeclarator.Parent as VariableDeclarationSyntax; return varDecl?.Parent switch { FieldDeclarationSyntax fieldDeclaration => fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.FieldName, LocalDeclarationStatementSyntax localDeclarationStatement => localDeclarationStatement.IsConst ? ClassificationTypeNames.ConstantName : ClassificationTypeNames.LocalName, EventFieldDeclarationSyntax _ => ClassificationTypeNames.EventName, _ => ClassificationTypeNames.LocalName, }; } else if (token.Parent is SingleVariableDesignationSyntax singleVariableDesignation && singleVariableDesignation.Identifier == token) { var parent = singleVariableDesignation.Parent; // Handle nested Tuple deconstruction while (parent.IsKind(SyntaxKind.ParenthesizedVariableDesignation)) { parent = parent.Parent; } // Checking for DeclarationExpression covers the following cases: // - Out parameters used within a field initializer or within a method. `int.TryParse("1", out var x)` // - Tuple deconstruction. `var (x, _) = (1, 2);` // // Checking for DeclarationPattern covers the following cases: // - Is patterns. `if (foo is Action action)` // - Switch patterns. `case int x when x > 0:` if (parent.IsKind(SyntaxKind.DeclarationExpression) || parent.IsKind(SyntaxKind.DeclarationPattern)) { return ClassificationTypeNames.LocalName; } return ClassificationTypeNames.Identifier; } else if (token.Parent is ParameterSyntax parameterSyntax && parameterSyntax.Identifier == token) { return ClassificationTypeNames.ParameterName; } else if (token.Parent is ForEachStatementSyntax forEachStatementSyntax && forEachStatementSyntax.Identifier == token) { return ClassificationTypeNames.LocalName; } else if (token.Parent is EventDeclarationSyntax eventDeclarationSyntax && eventDeclarationSyntax.Identifier == token) { return ClassificationTypeNames.EventName; } else if (IsActualContextualKeyword(token)) { return ClassificationTypeNames.Keyword; } else if (token.Parent is IdentifierNameSyntax identifierNameSyntax && IsNamespaceName(identifierNameSyntax)) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is ExternAliasDirectiveSyntax externAliasDirectiveSyntax && externAliasDirectiveSyntax.Identifier == token) { return ClassificationTypeNames.NamespaceName; } else if (token.Parent is LabeledStatementSyntax labledStatementSyntax && labledStatementSyntax.Identifier == token) { return ClassificationTypeNames.LabelName; } else { return ClassificationTypeNames.Identifier; } } private static string? GetClassificationTypeForConstructorOrDestructorParent(SyntaxNode parentNode) => parentNode.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null }; private static bool IsNamespaceName(IdentifierNameSyntax identifierSyntax) { var parent = identifierSyntax.Parent; while (parent is QualifiedNameSyntax) parent = parent.Parent; return parent is BaseNamespaceDeclarationSyntax; } public static bool IsStaticallyDeclared(SyntaxToken token) { var parentNode = token.Parent; if (parentNode.IsKind(SyntaxKind.EnumMemberDeclaration)) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } else if (parentNode.IsKind(SyntaxKind.VariableDeclarator)) { // The parent of a VariableDeclarator is a VariableDeclarationSyntax node. // It's parent will be the declaration syntax node. parentNode = parentNode!.Parent!.Parent; // Check if this is a field constant declaration if (parentNode.GetModifiers().Any(SyntaxKind.ConstKeyword)) { return true; } } return parentNode.GetModifiers().Any(SyntaxKind.StaticKeyword); } private static bool IsExtensionMethod(MethodDeclarationSyntax methodDeclaration) => methodDeclaration.ParameterList.Parameters.FirstOrDefault()?.Modifiers.Any(SyntaxKind.ThisKeyword) == true; private static string? GetClassificationForTypeDeclarationIdentifier(SyntaxToken identifier) => identifier.Parent!.Kind() switch { SyntaxKind.ClassDeclaration => ClassificationTypeNames.ClassName, SyntaxKind.EnumDeclaration => ClassificationTypeNames.EnumName, SyntaxKind.StructDeclaration => ClassificationTypeNames.StructName, SyntaxKind.InterfaceDeclaration => ClassificationTypeNames.InterfaceName, SyntaxKind.RecordDeclaration => ClassificationTypeNames.RecordClassName, SyntaxKind.RecordStructDeclaration => ClassificationTypeNames.RecordStructName, _ => null, }; private static string GetClassificationForPunctuation(SyntaxToken token) { if (token.Kind().IsOperator()) { // special cases... switch (token.Kind()) { case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: // the < and > tokens of a type parameter list or function pointer parameter // list should be classified as punctuation; otherwise, they're operators. if (token.Parent != null) { if (token.Parent.Kind() == SyntaxKind.TypeParameterList || token.Parent.Kind() == SyntaxKind.TypeArgumentList || token.Parent.Kind() == SyntaxKind.FunctionPointerParameterList) { return ClassificationTypeNames.Punctuation; } } break; case SyntaxKind.ColonToken: // the : for inheritance/implements or labels should be classified as // punctuation; otherwise, it's from a conditional operator. if (token.Parent != null) { if (token.Parent.Kind() != SyntaxKind.ConditionalExpression) { return ClassificationTypeNames.Punctuation; } } break; } return ClassificationTypeNames.Operator; } else { return ClassificationTypeNames.Punctuation; } } private static bool IsOperator(this SyntaxKind kind) { switch (kind) { case SyntaxKind.TildeToken: case SyntaxKind.ExclamationToken: case SyntaxKind.PercentToken: case SyntaxKind.CaretToken: case SyntaxKind.AmpersandToken: case SyntaxKind.AsteriskToken: case SyntaxKind.MinusToken: case SyntaxKind.PlusToken: case SyntaxKind.EqualsToken: case SyntaxKind.BarToken: case SyntaxKind.ColonToken: case SyntaxKind.LessThanToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.DotToken: case SyntaxKind.QuestionToken: case SyntaxKind.SlashToken: case SyntaxKind.BarBarToken: case SyntaxKind.AmpersandAmpersandToken: case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: case SyntaxKind.ColonColonToken: case SyntaxKind.QuestionQuestionToken: case SyntaxKind.MinusGreaterThanToken: case SyntaxKind.ExclamationEqualsToken: case SyntaxKind.EqualsEqualsToken: case SyntaxKind.EqualsGreaterThanToken: case SyntaxKind.LessThanEqualsToken: case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: case SyntaxKind.GreaterThanEqualsToken: case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: case SyntaxKind.SlashEqualsToken: case SyntaxKind.AsteriskEqualsToken: case SyntaxKind.BarEqualsToken: case SyntaxKind.AmpersandEqualsToken: case SyntaxKind.PlusEqualsToken: case SyntaxKind.MinusEqualsToken: case SyntaxKind.CaretEqualsToken: case SyntaxKind.PercentEqualsToken: case SyntaxKind.QuestionQuestionEqualsToken: return true; default: return false; } } private static bool IsActualContextualKeyword(SyntaxToken token) { if (token.Parent.IsKind(SyntaxKind.LabeledStatement, out LabeledStatementSyntax? statement) && statement.Identifier == token) { return false; } // Ensure that the text and value text are the same. Otherwise, the identifier might // be escaped. I.e. "var", but not "@var" if (token.ToString() != token.ValueText) { return false; } // Standard cases. We can just check the parent and see if we're // in the right position to be considered a contextual keyword if (token.Parent != null) { switch (token.ValueText) { case AwaitKeyword: return token.GetNextToken(includeZeroWidth: true).IsMissing; case FromKeyword: var fromClause = token.Parent.FirstAncestorOrSelf<FromClauseSyntax>(); return fromClause != null && fromClause.FromKeyword == token; case VarKeyword: // var if (token.Parent is IdentifierNameSyntax && token.Parent?.Parent is ExpressionStatementSyntax) { return true; } // we allow var any time it looks like a variable declaration, and is not in a // field or event field. return token.Parent is IdentifierNameSyntax && token.Parent.Parent is VariableDeclarationSyntax && !(token.Parent.Parent.Parent is FieldDeclarationSyntax) && !(token.Parent.Parent.Parent is EventFieldDeclarationSyntax); case UnmanagedKeyword: case NotNullKeyword: return token.Parent is IdentifierNameSyntax && token.Parent.Parent is TypeConstraintSyntax && token.Parent.Parent.Parent is TypeParameterConstraintClauseSyntax; } } return false; } internal static void AddLexicalClassifications(SourceText text, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { var text2 = text.ToString(textSpan); var tokens = SyntaxFactory.ParseTokens(text2, initialTokenPosition: textSpan.Start); Worker.CollectClassifiedSpans(tokens, textSpan, result, cancellationToken); } internal static ClassifiedSpan AdjustStaleClassification(SourceText rawText, ClassifiedSpan classifiedSpan) { // If we marked this as an identifier and it should now be a keyword // (or vice versa), then fix this up and return it. var classificationType = classifiedSpan.ClassificationType; // Check if the token's type has changed. Note: we don't check for "wasPPKeyword && // !isPPKeyword" here. That's because for fault tolerance any identifier will end up // being parsed as a PP keyword eventually, and if we have the check here, the text // flickers between blue and black while typing. See // http://vstfdevdiv:8080/web/wi.aspx?id=3521 for details. var wasKeyword = classificationType == ClassificationTypeNames.Keyword; var wasIdentifier = classificationType == ClassificationTypeNames.Identifier; // We only do this for identifiers/keywords. if (wasKeyword || wasIdentifier) { // Get the current text under the tag. var span = classifiedSpan.TextSpan; var text = rawText.ToString(span); // Now, try to find the token that corresponds to that text. If // we get 0 or 2+ tokens, then we can't do anything with this. // Also, if that text includes trivia, then we can't do anything. var token = SyntaxFactory.ParseToken(text); if (token.Span.Length == span.Length) { // var, dynamic, and unmanaged are not contextual keywords. They are always identifiers // (that we classify as keywords). Because we are just parsing a token we don't // know if we're in the right context for them to be identifiers or keywords. // So, we base on decision on what they were before. i.e. if we had a keyword // before, then assume it stays a keyword if we see 'var', 'dynamic', or 'unmanaged'. var tokenString = token.ToString(); var isKeyword = SyntaxFacts.IsKeywordKind(token.Kind()) || (wasKeyword && SyntaxFacts.GetContextualKeywordKind(text) != SyntaxKind.None) || (wasKeyword && (tokenString == VarKeyword || tokenString == DynamicKeyword || tokenString == UnmanagedKeyword || tokenString == NotNullKeyword)); var isIdentifier = token.Kind() == SyntaxKind.IdentifierToken; // We only do this for identifiers/keywords. if (isKeyword || isIdentifier) { if ((wasKeyword && !isKeyword) || (wasIdentifier && !isIdentifier)) { // It changed! Return the new type of tagspan. return new ClassifiedSpan( isKeyword ? ClassificationTypeNames.Keyword : ClassificationTypeNames.Identifier, span); } } } } // didn't need to do anything to this one. return classifiedSpan; } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; 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; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class CSharpCodeGenerationHelpers { public static TDeclarationSyntax ConditionallyAddFormattingAnnotationTo<TDeclarationSyntax>( TDeclarationSyntax result, SyntaxList<MemberDeclarationSyntax> members) where TDeclarationSyntax : MemberDeclarationSyntax { return members.Count == 1 ? result.WithAdditionalAnnotations(Formatter.Annotation) : result; } internal static void AddAccessibilityModifiers( Accessibility accessibility, ArrayBuilder<SyntaxToken> tokens, CodeGenerationOptions options, Accessibility defaultAccessibility) { options ??= CodeGenerationOptions.Default; if (!options.GenerateDefaultAccessibility && accessibility == defaultAccessibility) { return; } switch (accessibility) { case Accessibility.Public: tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Protected: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Private: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.ProtectedAndInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.Internal: tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.ProtectedOrInternal: tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); tokens.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; } } public static TypeDeclarationSyntax AddMembersTo( TypeDeclarationSyntax destination, SyntaxList<MemberDeclarationSyntax> members) { var syntaxTree = destination.SyntaxTree; destination = ReplaceUnterminatedConstructs(destination); var node = ConditionallyAddFormattingAnnotationTo( destination.EnsureOpenAndCloseBraceTokens().WithMembers(members), members); // Make sure the generated syntax node has same parse option. // e.g. If add syntax member to a C# 5 destination, we should return a C# 5 syntax node. var tree = node.SyntaxTree.WithRootAndOptions(node, syntaxTree.Options); return (TypeDeclarationSyntax)tree.GetRoot(); } private static TypeDeclarationSyntax ReplaceUnterminatedConstructs(TypeDeclarationSyntax destination) { const string MultiLineCommentTerminator = "*/"; var lastToken = destination.GetLastToken(); var updatedToken = lastToken.ReplaceTrivia(lastToken.TrailingTrivia, (t1, t2) => { if (t1.Kind() == SyntaxKind.MultiLineCommentTrivia) { var text = t1.ToString(); if (!text.EndsWith(MultiLineCommentTerminator, StringComparison.Ordinal)) { return SyntaxFactory.SyntaxTrivia(SyntaxKind.MultiLineCommentTrivia, text + MultiLineCommentTerminator); } } else if (t1.Kind() == SyntaxKind.SkippedTokensTrivia) { return ReplaceUnterminatedConstructs(t1); } return t1; }); return destination.ReplaceToken(lastToken, updatedToken); } private static SyntaxTrivia ReplaceUnterminatedConstructs(SyntaxTrivia skippedTokensTrivia) { var syntax = (SkippedTokensTriviaSyntax)skippedTokensTrivia.GetStructure(); var tokens = syntax.Tokens; var updatedTokens = SyntaxFactory.TokenList(tokens.Select(ReplaceUnterminatedConstruct)); var updatedSyntax = syntax.WithTokens(updatedTokens); return SyntaxFactory.Trivia(updatedSyntax); } private static SyntaxToken ReplaceUnterminatedConstruct(SyntaxToken token) { if (token.IsVerbatimStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 2 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } else if (token.IsRegularStringLiteral()) { var tokenText = token.ToString(); if (tokenText.Length <= 1 || tokenText.Last() != '"') { tokenText += '"'; return SyntaxFactory.Literal(token.LeadingTrivia, tokenText, token.ValueText, token.TrailingTrivia); } } return token; } public static MemberDeclarationSyntax FirstMember(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(); public static MemberDeclarationSyntax FirstMethod(SyntaxList<MemberDeclarationSyntax> members) => members.FirstOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastField(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is FieldDeclarationSyntax); public static MemberDeclarationSyntax LastConstructor(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is ConstructorDeclarationSyntax); public static MemberDeclarationSyntax LastMethod(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is MethodDeclarationSyntax); public static MemberDeclarationSyntax LastOperator(SyntaxList<MemberDeclarationSyntax> members) => members.LastOrDefault(m => m is OperatorDeclarationSyntax || m is ConversionOperatorDeclarationSyntax); public static SyntaxList<TDeclaration> Insert<TDeclaration>( SyntaxList<TDeclaration> declarationList, TDeclaration declaration, CodeGenerationOptions options, IList<bool> availableIndices, Func<SyntaxList<TDeclaration>, TDeclaration> after = null, Func<SyntaxList<TDeclaration>, TDeclaration> before = null) where TDeclaration : SyntaxNode { var index = GetInsertionIndex( declarationList, declaration, options, availableIndices, CSharpDeclarationComparer.WithoutNamesInstance, CSharpDeclarationComparer.WithNamesInstance, after, before); if (availableIndices != null) { availableIndices.Insert(index, true); } if (index != 0 && declarationList[index - 1].ContainsDiagnostics && AreBracesMissing(declarationList[index - 1])) { return declarationList.Insert(index, declaration.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return declarationList.Insert(index, declaration); } private static bool AreBracesMissing<TDeclaration>(TDeclaration declaration) where TDeclaration : SyntaxNode => declaration.ChildTokens().Where(t => t.IsKind(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) && t.IsMissing).Any(); public static SyntaxNode GetContextNode( Location location, CancellationToken cancellationToken) { var contextLocation = location as Location; var contextTree = contextLocation != null && contextLocation.IsInSource ? contextLocation.SourceTree : null; return contextTree?.GetRoot(cancellationToken).FindToken(contextLocation.SourceSpan.Start).Parent; } public static ExplicitInterfaceSpecifierSyntax GenerateExplicitInterfaceSpecifier( IEnumerable<ISymbol> implementations) { var implementation = implementations.FirstOrDefault(); if (implementation == null) { return null; } if (!(implementation.ContainingType.GenerateTypeSyntax() is NameSyntax name)) { return null; } return SyntaxFactory.ExplicitInterfaceSpecifier(name); } public static CodeGenerationDestination GetDestination(SyntaxNode destination) { if (destination != null) { return destination.Kind() switch { SyntaxKind.ClassDeclaration => CodeGenerationDestination.ClassType, SyntaxKind.CompilationUnit => CodeGenerationDestination.CompilationUnit, SyntaxKind.EnumDeclaration => CodeGenerationDestination.EnumType, SyntaxKind.InterfaceDeclaration => CodeGenerationDestination.InterfaceType, SyntaxKind.FileScopedNamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.NamespaceDeclaration => CodeGenerationDestination.Namespace, SyntaxKind.StructDeclaration => CodeGenerationDestination.StructType, _ => CodeGenerationDestination.Unspecified, }; } return CodeGenerationDestination.Unspecified; } public static TSyntaxNode ConditionallyAddDocumentationCommentTo<TSyntaxNode>( TSyntaxNode node, ISymbol symbol, CodeGenerationOptions options, CancellationToken cancellationToken = default) where TSyntaxNode : SyntaxNode { if (!options.GenerateDocumentationComments || node.GetLeadingTrivia().Any(t => t.IsDocComment())) { return node; } var result = TryGetDocumentationComment(symbol, "///", out var comment, cancellationToken) ? node.WithPrependedLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(comment)) .WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) : node; return result; } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal partial class CSharpCodeGenerationService : AbstractCodeGenerationService { public CSharpCodeGenerationService(HostLanguageServices languageServices) : base(languageServices.GetService<ISymbolDeclarationService>(), languageServices.WorkspaceServices.Workspace) { } public override CodeGenerationDestination GetDestination(SyntaxNode node) => CSharpCodeGenerationHelpers.GetDestination(node); protected override IComparer<SyntaxNode> GetMemberComparer() => CSharpDeclarationComparer.WithoutNamesInstance; protected override IList<bool> GetAvailableInsertionIndices(SyntaxNode destination, CancellationToken cancellationToken) { if (destination is TypeDeclarationSyntax typeDeclaration) { return GetInsertionIndices(typeDeclaration, cancellationToken); } // TODO(cyrusn): This will make is so that we can't generate into an enum, namespace, or // compilation unit, if it overlaps a hidden region. We can consider relaxing that // restriction in the future. return null; } private static IList<bool> GetInsertionIndices(TypeDeclarationSyntax destination, CancellationToken cancellationToken) => destination.GetInsertionIndices(cancellationToken); public override async Task<Document> AddEventAsync( Solution solution, INamedTypeSymbol destination, IEventSymbol @event, CodeGenerationOptions options, CancellationToken cancellationToken) { var newDocument = await base.AddEventAsync( solution, destination, @event, options, cancellationToken).ConfigureAwait(false); var namedType = @event.Type as INamedTypeSymbol; if (namedType?.AssociatedSymbol != null) { // This is a VB event that declares its own type. i.e. "Public Event E(x As Object)" // We also have to generate "public void delegate EEventHandler(object x)" var compilation = await newDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newDestinationSymbol = destination.GetSymbolKey(cancellationToken).Resolve(compilation, cancellationToken: cancellationToken).Symbol; if (newDestinationSymbol?.ContainingType != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingType, namedType, options, cancellationToken).ConfigureAwait(false); } else if (newDestinationSymbol?.ContainingNamespace != null) { return await this.AddNamedTypeAsync( newDocument.Project.Solution, newDestinationSymbol.ContainingNamespace, namedType, options, cancellationToken).ConfigureAwait(false); } } return newDocument; } protected override TDeclarationNode AddEvent<TDeclarationNode>(TDeclarationNode destination, IEventSymbol @event, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax>(destination); return Cast<TDeclarationNode>(EventGenerator.AddEventTo(Cast<TypeDeclarationSyntax>(destination), @event, options, availableIndices)); } protected override TDeclarationNode AddField<TDeclarationNode>(TDeclarationNode destination, IFieldSymbol field, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax) { return Cast<TDeclarationNode>(EnumMemberGenerator.AddEnumMemberTo(Cast<EnumDeclarationSyntax>(destination), field, options)); } else if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<TypeDeclarationSyntax>(destination), field, options, availableIndices)); } else { return Cast<TDeclarationNode>(FieldGenerator.AddFieldTo(Cast<CompilationUnitSyntax>(destination), field, options, availableIndices)); } } protected override TDeclarationNode AddMethod<TDeclarationNode>(TDeclarationNode destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { // https://github.com/dotnet/roslyn/issues/44425: Add handling for top level statements if (destination is GlobalStatementSyntax) { return destination; } CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); options = options.With(options: options.Options ?? Workspace.Options); // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return destination; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return destination; } } if (destination is TypeDeclarationSyntax typeDeclaration) { if (method.IsConstructor()) { return Cast<TDeclarationNode>(ConstructorGenerator.AddConstructorTo( typeDeclaration, method, options, availableIndices)); } if (method.IsDestructor()) { return Cast<TDeclarationNode>(DestructorGenerator.AddDestructorTo(typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.Conversion) { return Cast<TDeclarationNode>(ConversionGenerator.AddConversionTo( typeDeclaration, method, options, availableIndices)); } if (method.MethodKind == MethodKind.UserDefinedOperator) { return Cast<TDeclarationNode>(OperatorGenerator.AddOperatorTo( typeDeclaration, method, options, availableIndices)); } return Cast<TDeclarationNode>(MethodGenerator.AddMethodTo( typeDeclaration, method, options, availableIndices)); } if (method.IsConstructor() || method.IsDestructor()) { return destination; } if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices)); } var ns = Cast<BaseNamespaceDeclarationSyntax>(destination); return Cast<TDeclarationNode>( MethodGenerator.AddMethodTo(ns, method, options, availableIndices)); } protected override TDeclarationNode AddProperty<TDeclarationNode>(TDeclarationNode destination, IPropertySymbol property, CodeGenerationOptions options, IList<bool> availableIndices) { CheckDeclarationNode<TypeDeclarationSyntax, CompilationUnitSyntax>(destination); // Can't generate a property with parameters. So generate the setter/getter individually. if (!PropertyGenerator.CanBeGenerated(property)) { var members = new List<ISymbol>(); if (property.GetMethod != null) { var getMethod = property.GetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { getMethod = annotation.AddAnnotationToSymbol(getMethod); } } members.Add(getMethod); } if (property.SetMethod != null) { var setMethod = property.SetMethod; if (property is CodeGenerationSymbol codeGenSymbol) { foreach (var annotation in codeGenSymbol.GetAnnotations()) { setMethod = annotation.AddAnnotationToSymbol(setMethod); } } members.Add(setMethod); } if (members.Count > 1) { options = CreateOptionsForMultipleMembers(options); } return AddMembers(destination, members, availableIndices, options, CancellationToken.None); } if (destination is TypeDeclarationSyntax) { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<TypeDeclarationSyntax>(destination), property, options, availableIndices)); } else { return Cast<TDeclarationNode>(PropertyGenerator.AddPropertyTo( Cast<CompilationUnitSyntax>(destination), property, options, availableIndices)); } } protected override TDeclarationNode AddNamedType<TDeclarationNode>(TDeclarationNode destination, INamedTypeSymbol namedType, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, typeDeclaration, namedType, options, availableIndices, cancellationToken)); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, namespaceDeclaration, namedType, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamedTypeGenerator.AddNamedTypeTo(this, Cast<CompilationUnitSyntax>(destination), namedType, options, availableIndices, cancellationToken)); } } protected override TDeclarationNode AddNamespace<TDeclarationNode>(TDeclarationNode destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { CheckDeclarationNode<CompilationUnitSyntax, BaseNamespaceDeclarationSyntax>(destination); if (destination is CompilationUnitSyntax compilationUnit) { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, compilationUnit, @namespace, options, availableIndices, cancellationToken)); } else { return Cast<TDeclarationNode>(NamespaceGenerator.AddNamespaceTo(this, Cast<BaseNamespaceDeclarationSyntax>(destination), @namespace, options, availableIndices, cancellationToken)); } } public override TDeclarationNode AddParameters<TDeclarationNode>( TDeclarationNode destination, IEnumerable<IParameterSymbol> parameters, CodeGenerationOptions options, CancellationToken cancellationToken) { var currentParameterList = destination.GetParameterList(); if (currentParameterList == null) { return destination; } var currentParamsCount = currentParameterList.Parameters.Count; var seenOptional = currentParamsCount > 0 && currentParameterList.Parameters[currentParamsCount - 1].Default != null; var isFirstParam = currentParamsCount == 0; var newParams = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var parameter in parameters) { var parameterSyntax = ParameterGenerator.GetParameter(parameter, options, isExplicit: false, isFirstParam: isFirstParam, seenOptional: seenOptional); isFirstParam = false; seenOptional = seenOptional || parameterSyntax.Default != null; newParams.Add(parameterSyntax); } var finalMember = CSharpSyntaxGenerator.Instance.AddParameters(destination, newParams.ToImmutableAndFree()); return Cast<TDeclarationNode>(finalMember); } public override TDeclarationNode AddAttributes<TDeclarationNode>( TDeclarationNode destination, IEnumerable<AttributeData> attributes, SyntaxToken? target, CodeGenerationOptions options, CancellationToken cancellationToken) { if (target.HasValue && !target.Value.IsValidAttributeTarget()) { throw new ArgumentException("target"); } var attributeSyntaxList = AttributeGenerator.GenerateAttributeLists(attributes.ToImmutableArray(), options, target).ToArray(); return destination switch { MemberDeclarationSyntax member => Cast<TDeclarationNode>(member.AddAttributeLists(attributeSyntaxList)), AccessorDeclarationSyntax accessor => Cast<TDeclarationNode>(accessor.AddAttributeLists(attributeSyntaxList)), CompilationUnitSyntax compilationUnit => Cast<TDeclarationNode>(compilationUnit.AddAttributeLists(attributeSyntaxList)), ParameterSyntax parameter => Cast<TDeclarationNode>(parameter.AddAttributeLists(attributeSyntaxList)), TypeParameterSyntax typeParameter => Cast<TDeclarationNode>(typeParameter.AddAttributeLists(attributeSyntaxList)), _ => destination, }; } protected override TDeclarationNode AddMembers<TDeclarationNode>(TDeclarationNode destination, IEnumerable<SyntaxNode> members) { CheckDeclarationNode<EnumDeclarationSyntax, TypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, CompilationUnitSyntax>(destination); if (destination is EnumDeclarationSyntax enumDeclaration) { return Cast<TDeclarationNode>(enumDeclaration.AddMembers(members.Cast<EnumMemberDeclarationSyntax>().ToArray())); } else if (destination is TypeDeclarationSyntax typeDeclaration) { return Cast<TDeclarationNode>(typeDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else if (destination is BaseNamespaceDeclarationSyntax namespaceDeclaration) { return Cast<TDeclarationNode>(namespaceDeclaration.AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } else { return Cast<TDeclarationNode>(Cast<CompilationUnitSyntax>(destination) .AddMembers(members.Cast<MemberDeclarationSyntax>().ToArray())); } } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, AttributeData attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove.ApplicationSyntaxReference == null) { throw new ArgumentException("attributeToRemove"); } var attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken); return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken); } public override TDeclarationNode RemoveAttribute<TDeclarationNode>( TDeclarationNode destination, SyntaxNode attributeToRemove, CodeGenerationOptions options, CancellationToken cancellationToken) { if (attributeToRemove == null) { throw new ArgumentException("attributeToRemove"); } // Removed node could be AttributeSyntax or AttributeListSyntax. int positionOfRemovedNode; SyntaxTriviaList triviaOfRemovedNode; switch (destination) { case MemberDeclarationSyntax member: { // Handle all members including types. var newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newMember = member.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case AccessorDeclarationSyntax accessor: { // Handle accessors var newAttributeLists = RemoveAttributeFromAttributeLists(accessor.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newAccessor = accessor.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newAccessor, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case CompilationUnitSyntax compilationUnit: { // Handle global attributes var newAttributeLists = RemoveAttributeFromAttributeLists(compilationUnit.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newCompilationUnit = compilationUnit.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case ParameterSyntax parameter: { // Handle parameters var newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newParameter = parameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } case TypeParameterSyntax typeParameter: { var newAttributeLists = RemoveAttributeFromAttributeLists(typeParameter.AttributeLists, attributeToRemove, out positionOfRemovedNode, out triviaOfRemovedNode); var newTypeParameter = typeParameter.WithAttributeLists(newAttributeLists); return Cast<TDeclarationNode>(AppendTriviaAtPosition(newTypeParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode)); } } return destination; } private static SyntaxList<AttributeListSyntax> RemoveAttributeFromAttributeLists( SyntaxList<AttributeListSyntax> attributeLists, SyntaxNode attributeToRemove, out int positionOfRemovedNode, out SyntaxTriviaList triviaOfRemovedNode) { foreach (var attributeList in attributeLists) { var attributes = attributeList.Attributes; if (attributes.Contains(attributeToRemove)) { IEnumerable<SyntaxTrivia> trivia; IEnumerable<AttributeListSyntax> newAttributeLists; if (attributes.Count == 1) { // Remove the entire attribute list. ComputePositionAndTriviaForRemoveAttributeList(attributeList, (SyntaxTrivia t) => t.IsKind(SyntaxKind.EndOfLineTrivia), out positionOfRemovedNode, out trivia); newAttributeLists = attributeLists.Where(aList => aList != attributeList); } else { // Remove just the given attribute from the attribute list. ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, (SyntaxToken t) => t.IsKind(SyntaxKind.CommaToken), out positionOfRemovedNode, out trivia); var newAttributes = SyntaxFactory.SeparatedList(attributes.Where(a => a != attributeToRemove)); var newAttributeList = attributeList.WithAttributes(newAttributes); newAttributeLists = attributeLists.Select(attrList => attrList == attributeList ? newAttributeList : attrList); } triviaOfRemovedNode = trivia.ToSyntaxTriviaList(); return newAttributeLists.ToSyntaxList(); } } throw new ArgumentException("attributeToRemove"); } public override TDeclarationNode AddStatements<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) { if (destinationMember is MemberDeclarationSyntax memberDeclaration) { return AddStatementsToMemberDeclaration<TDeclarationNode>(destinationMember, statements, memberDeclaration); } else if (destinationMember is LocalFunctionStatementSyntax localFunctionDeclaration) { return (localFunctionDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(localFunctionDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is AccessorDeclarationSyntax accessorDeclaration) { return (accessorDeclaration.Body == null) ? destinationMember : Cast<TDeclarationNode>(accessorDeclaration.AddBodyStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else if (destinationMember is CompilationUnitSyntax compilationUnit && options is null) { // This path supports top-level statement insertion. It only applies when 'options' // is null so the fallback code below can handle cases where the insertion location // is provided through options.BestLocation. // // Insert the new global statement(s) at the end of any current global statements. // This code relies on 'LastIndexOf' returning -1 when no matching element is found. var insertionIndex = compilationUnit.Members.LastIndexOf(memberDeclaration => memberDeclaration.IsKind(SyntaxKind.GlobalStatement)) + 1; var wrappedStatements = StatementGenerator.GenerateStatements(statements).Select(generated => SyntaxFactory.GlobalStatement(generated)).ToArray(); return Cast<TDeclarationNode>(compilationUnit.WithMembers(compilationUnit.Members.InsertRange(insertionIndex, wrappedStatements))); } else if (destinationMember is StatementSyntax statement && statement.IsParentKind(SyntaxKind.GlobalStatement)) { // We are adding a statement to a global statement in script, where the CompilationUnitSyntax is not a // statement container. If the global statement is not already a block, create a block which can hold // both the original statement and any new statements we are adding to it. var block = statement as BlockSyntax ?? SyntaxFactory.Block(statement); return Cast<TDeclarationNode>(block.AddStatements(StatementGenerator.GenerateStatements(statements).ToArray())); } else { return AddStatementsWorker(destinationMember, statements, options, cancellationToken); } } private static TDeclarationNode AddStatementsWorker<TDeclarationNode>( TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, CodeGenerationOptions options, CancellationToken cancellationToken) where TDeclarationNode : SyntaxNode { var location = options.BestLocation; CheckLocation<TDeclarationNode>(destinationMember, location); var token = location.FindToken(cancellationToken); var block = token.Parent.GetAncestorsOrThis<BlockSyntax>().FirstOrDefault(); if (block != null) { var blockStatements = block.Statements.ToSet(); var containingStatement = token.GetAncestors<StatementSyntax>().Single(blockStatements.Contains); var index = block.Statements.IndexOf(containingStatement); var newStatements = statements.OfType<StatementSyntax>().ToArray(); BlockSyntax newBlock; if (options.BeforeThisLocation != null) { var newContainingStatement = containingStatement.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var strippedTrivia); newStatements[0] = newStatements[0].WithLeadingTrivia(strippedTrivia); newBlock = block.ReplaceNode(containingStatement, newContainingStatement); newBlock = newBlock.WithStatements(newBlock.Statements.InsertRange(index, newStatements)); } else { newBlock = block.WithStatements(block.Statements.InsertRange(index + 1, newStatements)); } return destinationMember.ReplaceNode(block, newBlock); } throw new ArgumentException(CSharpWorkspaceResources.No_available_location_found_to_add_statements_to); } private static TDeclarationNode AddStatementsToMemberDeclaration<TDeclarationNode>(TDeclarationNode destinationMember, IEnumerable<SyntaxNode> statements, MemberDeclarationSyntax memberDeclaration) where TDeclarationNode : SyntaxNode { var body = memberDeclaration.GetBody(); if (body == null) { return destinationMember; } var statementNodes = body.Statements.ToList(); statementNodes.AddRange(StatementGenerator.GenerateStatements(statements)); var finalBody = body.WithStatements(SyntaxFactory.List<StatementSyntax>(statementNodes)); var finalMember = memberDeclaration.WithBody(finalBody); return Cast<TDeclarationNode>(finalMember); } public override SyntaxNode CreateEventDeclaration( IEventSymbol @event, CodeGenerationDestination destination, CodeGenerationOptions options) { return EventGenerator.GenerateEventDeclaration(@event, destination, options); } public override SyntaxNode CreateFieldDeclaration(IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { return destination == CodeGenerationDestination.EnumType ? EnumMemberGenerator.GenerateEnumMemberDeclaration(field, null, options) : (SyntaxNode)FieldGenerator.GenerateFieldDeclaration(field, options); } public override SyntaxNode CreateMethodDeclaration( IMethodSymbol method, CodeGenerationDestination destination, CodeGenerationOptions options) { // Synthesized methods for properties/events are not things we actually generate // declarations for. if (method.AssociatedSymbol is IEventSymbol) { return null; } // we will ignore the method if the associated property can be generated. if (method.AssociatedSymbol is IPropertySymbol property) { if (PropertyGenerator.CanBeGenerated(property)) { return null; } } if (method.IsDestructor()) { return DestructorGenerator.GenerateDestructorDeclaration(method, options); } options = options.With(options: options.Options ?? Workspace.Options); if (method.IsConstructor()) { return ConstructorGenerator.GenerateConstructorDeclaration( method, options, options.ParseOptions); } else if (method.IsUserDefinedOperator()) { return OperatorGenerator.GenerateOperatorDeclaration( method, options, options.ParseOptions); } else if (method.IsConversion()) { return ConversionGenerator.GenerateConversionDeclaration( method, options, options.ParseOptions); } else if (method.IsLocalFunction()) { return MethodGenerator.GenerateLocalFunctionDeclaration( method, destination, options, options.ParseOptions); } else { return MethodGenerator.GenerateMethodDeclaration( method, destination, options, options.ParseOptions); } } public override SyntaxNode CreatePropertyDeclaration( IPropertySymbol property, CodeGenerationDestination destination, CodeGenerationOptions options) { return PropertyGenerator.GeneratePropertyOrIndexer( property, destination, options, options.ParseOptions); } public override SyntaxNode CreateNamedTypeDeclaration( INamedTypeSymbol namedType, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamedTypeGenerator.GenerateNamedTypeDeclaration(this, namedType, destination, options, cancellationToken); } public override SyntaxNode CreateNamespaceDeclaration( INamespaceSymbol @namespace, CodeGenerationDestination destination, CodeGenerationOptions options, CancellationToken cancellationToken) { return NamespaceGenerator.GenerateNamespaceDeclaration(this, @namespace, options, cancellationToken); } private static TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, Func<SyntaxTokenList, SyntaxTokenList> computeNewModifiersList) => declaration switch { BaseTypeDeclarationSyntax typeDeclaration => Cast<TDeclarationNode>(typeDeclaration.WithModifiers(computeNewModifiersList(typeDeclaration.Modifiers))), BaseFieldDeclarationSyntax fieldDeclaration => Cast<TDeclarationNode>(fieldDeclaration.WithModifiers(computeNewModifiersList(fieldDeclaration.Modifiers))), BaseMethodDeclarationSyntax methodDeclaration => Cast<TDeclarationNode>(methodDeclaration.WithModifiers(computeNewModifiersList(methodDeclaration.Modifiers))), BasePropertyDeclarationSyntax propertyDeclaration => Cast<TDeclarationNode>(propertyDeclaration.WithModifiers(computeNewModifiersList(propertyDeclaration.Modifiers))), _ => declaration, }; public override TDeclarationNode UpdateDeclarationModifiers<TDeclarationNode>(TDeclarationNode declaration, IEnumerable<SyntaxToken> newModifiers, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => newModifiers.ToSyntaxTokenList(); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } public override TDeclarationNode UpdateDeclarationAccessibility<TDeclarationNode>(TDeclarationNode declaration, Accessibility newAccessibility, CodeGenerationOptions options, CancellationToken cancellationToken) { SyntaxTokenList computeNewModifiersList(SyntaxTokenList modifiersList) => UpdateDeclarationAccessibility(modifiersList, newAccessibility, options); return UpdateDeclarationModifiers(declaration, computeNewModifiersList); } private static SyntaxTokenList UpdateDeclarationAccessibility(SyntaxTokenList modifiersList, Accessibility newAccessibility, CodeGenerationOptions options) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var newModifierTokens); CSharpCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, options, Accessibility.NotApplicable); if (newModifierTokens.Count == 0) { return modifiersList; } // TODO: Move more APIs to use pooled ArrayBuilder // https://github.com/dotnet/roslyn/issues/34960 return GetUpdatedDeclarationAccessibilityModifiers( newModifierTokens, modifiersList, modifier => SyntaxFacts.IsAccessibilityModifier(modifier.Kind())); } public override TDeclarationNode UpdateDeclarationType<TDeclarationNode>(TDeclarationNode declaration, ITypeSymbol newType, CodeGenerationOptions options, CancellationToken cancellationToken) { if (!(declaration is CSharpSyntaxNode syntaxNode)) { return declaration; } TypeSyntax newTypeSyntax; switch (syntaxNode.Kind()) { case SyntaxKind.DelegateDeclaration: // Handle delegate declarations. var delegateDeclarationSyntax = declaration as DelegateDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(delegateDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(delegateDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(delegateDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.MethodDeclaration: // Handle method declarations. var methodDeclarationSyntax = declaration as MethodDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(methodDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(methodDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(methodDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.OperatorDeclaration: // Handle operator declarations. var operatorDeclarationSyntax = declaration as OperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(operatorDeclarationSyntax.ReturnType.GetLeadingTrivia()) .WithTrailingTrivia(operatorDeclarationSyntax.ReturnType.GetTrailingTrivia()); return Cast<TDeclarationNode>(operatorDeclarationSyntax.WithReturnType(newTypeSyntax)); case SyntaxKind.ConversionOperatorDeclaration: // Handle conversion operator declarations. var conversionOperatorDeclarationSyntax = declaration as ConversionOperatorDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(conversionOperatorDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(conversionOperatorDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(conversionOperatorDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.PropertyDeclaration: // Handle properties. var propertyDeclaration = declaration as PropertyDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(propertyDeclaration.Type.GetLeadingTrivia()) .WithTrailingTrivia(propertyDeclaration.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(propertyDeclaration.WithType(newTypeSyntax)); case SyntaxKind.EventDeclaration: // Handle events. var eventDeclarationSyntax = declaration as EventDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(eventDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(eventDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(eventDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.IndexerDeclaration: // Handle indexers. var indexerDeclarationSyntax = declaration as IndexerDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(indexerDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(indexerDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(indexerDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.Parameter: // Handle parameters. var parameterSyntax = declaration as ParameterSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(parameterSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(parameterSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(parameterSyntax.WithType(newTypeSyntax)); case SyntaxKind.IncompleteMember: // Handle incomplete members. var incompleteMemberSyntax = declaration as IncompleteMemberSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(incompleteMemberSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(incompleteMemberSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(incompleteMemberSyntax.WithType(newTypeSyntax)); case SyntaxKind.ArrayType: // Handle array type. var arrayTypeSyntax = declaration as ArrayTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(arrayTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(arrayTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(arrayTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.PointerType: // Handle pointer type. var pointerTypeSyntax = declaration as PointerTypeSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(pointerTypeSyntax.ElementType.GetLeadingTrivia()) .WithTrailingTrivia(pointerTypeSyntax.ElementType.GetTrailingTrivia()); return Cast<TDeclarationNode>(pointerTypeSyntax.WithElementType(newTypeSyntax)); case SyntaxKind.VariableDeclaration: // Handle variable declarations. var variableDeclarationSyntax = declaration as VariableDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(variableDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(variableDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(variableDeclarationSyntax.WithType(newTypeSyntax)); case SyntaxKind.CatchDeclaration: // Handle catch declarations. var catchDeclarationSyntax = declaration as CatchDeclarationSyntax; newTypeSyntax = newType.GenerateTypeSyntax() .WithLeadingTrivia(catchDeclarationSyntax.Type.GetLeadingTrivia()) .WithTrailingTrivia(catchDeclarationSyntax.Type.GetTrailingTrivia()); return Cast<TDeclarationNode>(catchDeclarationSyntax.WithType(newTypeSyntax)); default: return declaration; } } public override TDeclarationNode UpdateDeclarationMembers<TDeclarationNode>(TDeclarationNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options = null, CancellationToken cancellationToken = default) { if (declaration is MemberDeclarationSyntax memberDeclaration) { return Cast<TDeclarationNode>(NamedTypeGenerator.UpdateNamedTypeDeclaration(this, memberDeclaration, newMembers, options, cancellationToken)); } if (declaration is CSharpSyntaxNode syntaxNode) { switch (syntaxNode.Kind()) { case SyntaxKind.CompilationUnit: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return Cast<TDeclarationNode>(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(this, syntaxNode, newMembers, options, cancellationToken)); } } return declaration; } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpSyntaxGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.Usings, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); return declaration switch { CompilationUnitSyntax cu => cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)), BaseNamespaceDeclarationSyntax nd => nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)), _ => declaration, }; } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, BaseNamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), BaseNamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) => declaration switch { InterfaceDeclarationSyntax => this.AsInterfaceMember(member), TypeDeclarationSyntax typeDeclaration => this.AsClassMember(member, typeDeclaration.Identifier.Text), EnumDeclarationSyntax => this.AsEnumMember(member), BaseNamespaceDeclarationSyntax => AsNamespaceMember(member), CompilationUnitSyntax => AsNamespaceMember(member), _ => null, }; public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), BaseNamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageService(typeof(SyntaxGenerator), LanguageNames.CSharp), Shared] internal class CSharpSyntaxGenerator : SyntaxGenerator { // A bit hacky, but we need to actually run ParseToken on the "nameof" text as there's no // other way to get a token back that has the appropriate internal bit set that indicates // this has the .ContextualKind of SyntaxKind.NameOfKeyword. private static readonly IdentifierNameSyntax s_nameOfIdentifier = SyntaxFactory.IdentifierName(SyntaxFactory.ParseToken("nameof")); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Incorrectly used in production code: https://github.com/dotnet/roslyn/issues/42839")] public CSharpSyntaxGenerator() { } internal override SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; internal override SyntaxTrivia CarriageReturnLineFeed => SyntaxFactory.CarriageReturnLineFeed; internal override bool RequiresExplicitImplementationForInterfaceMembers => false; internal override SyntaxGeneratorInternal SyntaxGeneratorInternal => CSharpSyntaxGeneratorInternal.Instance; internal override SyntaxTrivia Whitespace(string text) => SyntaxFactory.Whitespace(text); internal override SyntaxTrivia SingleLineComment(string text) => SyntaxFactory.Comment("//" + text); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(SyntaxNodeOrTokenList list) => SyntaxFactory.SeparatedList<TElement>(list); internal override SyntaxToken CreateInterpolatedStringStartToken(bool isVerbatim) { const string InterpolatedVerbatimText = "$@\""; return isVerbatim ? SyntaxFactory.Token(default, SyntaxKind.InterpolatedVerbatimStringStartToken, InterpolatedVerbatimText, InterpolatedVerbatimText, default) : SyntaxFactory.Token(SyntaxKind.InterpolatedStringStartToken); } internal override SyntaxToken CreateInterpolatedStringEndToken() => SyntaxFactory.Token(SyntaxKind.InterpolatedStringEndToken); internal override SeparatedSyntaxList<TElement> SeparatedList<TElement>(IEnumerable<TElement> nodes, IEnumerable<SyntaxToken> separators) => SyntaxFactory.SeparatedList(nodes, separators); internal override SyntaxTrivia Trivia(SyntaxNode node) { if (node is StructuredTriviaSyntax structuredTriviaSyntax) { return SyntaxFactory.Trivia(structuredTriviaSyntax); } throw ExceptionUtilities.UnexpectedValue(node.Kind()); } internal override SyntaxNode DocumentationCommentTrivia(IEnumerable<SyntaxNode> nodes, SyntaxTriviaList trailingTrivia, SyntaxTrivia lastWhitespaceTrivia, string endOfLineString) { var docTrivia = SyntaxFactory.DocumentationCommentTrivia( SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(nodes), SyntaxFactory.Token(SyntaxKind.EndOfDocumentationCommentToken)); docTrivia = docTrivia.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// ")) .WithTrailingTrivia(trailingTrivia); if (lastWhitespaceTrivia == default) return docTrivia.WithTrailingTrivia(SyntaxFactory.EndOfLine(endOfLineString)); return docTrivia.WithTrailingTrivia( SyntaxFactory.EndOfLine(endOfLineString), lastWhitespaceTrivia); } internal override SyntaxNode DocumentationCommentTriviaWithUpdatedContent(SyntaxTrivia trivia, IEnumerable<SyntaxNode> content) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return SyntaxFactory.DocumentationCommentTrivia(documentationCommentTrivia.Kind(), SyntaxFactory.List(content), documentationCommentTrivia.EndOfComment); } return null; } public static readonly SyntaxGenerator Instance = new CSharpSyntaxGenerator(); #region Declarations public override SyntaxNode CompilationUnit(IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.CompilationUnit() .WithUsings(this.AsUsingDirectives(declarations)) .WithMembers(AsNamespaceMembers(declarations)); } private SyntaxList<UsingDirectiveSyntax> AsUsingDirectives(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(this.AsUsingDirective).OfType<UsingDirectiveSyntax>()) : default; } private SyntaxNode AsUsingDirective(SyntaxNode node) { if (node is NameSyntax name) { return this.NamespaceImportDeclaration(name); } return node as UsingDirectiveSyntax; } private static SyntaxList<MemberDeclarationSyntax> AsNamespaceMembers(IEnumerable<SyntaxNode> declarations) { return declarations != null ? SyntaxFactory.List(declarations.Select(AsNamespaceMember).OfType<MemberDeclarationSyntax>()) : default; } private static SyntaxNode AsNamespaceMember(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return declaration; default: return null; } } public override SyntaxNode NamespaceImportDeclaration(SyntaxNode name) => SyntaxFactory.UsingDirective((NameSyntax)name); public override SyntaxNode AliasImportDeclaration(string aliasIdentifierName, SyntaxNode name) => SyntaxFactory.UsingDirective(SyntaxFactory.NameEquals(aliasIdentifierName), (NameSyntax)name); public override SyntaxNode NamespaceDeclaration(SyntaxNode name, IEnumerable<SyntaxNode> declarations) { return SyntaxFactory.NamespaceDeclaration( (NameSyntax)name, default, this.AsUsingDirectives(declarations), AsNamespaceMembers(declarations)); } public override SyntaxNode FieldDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode initializer) { return SyntaxFactory.FieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.FieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator( name.ToIdentifierToken(), null, initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null)))); } public override SyntaxNode ParameterDeclaration(string name, SyntaxNode type, SyntaxNode initializer, RefKind refKind) { return SyntaxFactory.Parameter( default, CSharpSyntaxGeneratorInternal.GetParameterModifiers(refKind), (TypeSyntax)type, name.ToIdentifierToken(), initializer != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)initializer) : null); } internal static SyntaxToken GetArgumentModifiers(RefKind refKind) { switch (refKind) { case RefKind.None: case RefKind.In: return default; case RefKind.Out: return SyntaxFactory.Token(SyntaxKind.OutKeyword); case RefKind.Ref: return SyntaxFactory.Token(SyntaxKind.RefKeyword); default: throw ExceptionUtilities.UnexpectedValue(refKind); } } public override SyntaxNode MethodDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> statements) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); return SyntaxFactory.MethodDeclaration( attributeLists: default, modifiers: AsModifierList(accessibility, modifiers, SyntaxKind.MethodDeclaration), returnType: returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), explicitInterfaceSpecifier: null, identifier: name.ToIdentifierToken(), typeParameterList: AsTypeParameterList(typeParameters), parameterList: AsParameterList(parameters), constraintClauses: default, body: hasBody ? CreateBlock(statements) : null, expressionBody: null, semicolonToken: !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default); } public override SyntaxNode OperatorDeclaration(OperatorKind kind, IEnumerable<SyntaxNode> parameters = null, SyntaxNode returnType = null, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> statements = null) { var hasBody = !modifiers.IsAbstract && (!modifiers.IsPartial || statements != null); var returnTypeNode = returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); var parameterList = AsParameterList(parameters); var body = hasBody ? CreateBlock(statements) : null; var semicolon = !hasBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; var modifierList = AsModifierList(accessibility, modifiers, SyntaxKind.OperatorDeclaration); var attributes = default(SyntaxList<AttributeListSyntax>); if (kind == OperatorKind.ImplicitConversion || kind == OperatorKind.ExplicitConversion) { return SyntaxFactory.ConversionOperatorDeclaration( attributes, modifierList, SyntaxFactory.Token(GetTokenKind(kind)), SyntaxFactory.Token(SyntaxKind.OperatorKeyword), returnTypeNode, parameterList, body, semicolon); } else { return SyntaxFactory.OperatorDeclaration( attributes, modifierList, returnTypeNode, SyntaxFactory.Token(SyntaxKind.OperatorKeyword), SyntaxFactory.Token(GetTokenKind(kind)), parameterList, body, semicolon); } } private static SyntaxKind GetTokenKind(OperatorKind kind) => kind switch { OperatorKind.ImplicitConversion => SyntaxKind.ImplicitKeyword, OperatorKind.ExplicitConversion => SyntaxKind.ExplicitKeyword, OperatorKind.Addition => SyntaxKind.PlusToken, OperatorKind.BitwiseAnd => SyntaxKind.AmpersandToken, OperatorKind.BitwiseOr => SyntaxKind.BarToken, OperatorKind.Decrement => SyntaxKind.MinusMinusToken, OperatorKind.Division => SyntaxKind.SlashToken, OperatorKind.Equality => SyntaxKind.EqualsEqualsToken, OperatorKind.ExclusiveOr => SyntaxKind.CaretToken, OperatorKind.False => SyntaxKind.FalseKeyword, OperatorKind.GreaterThan => SyntaxKind.GreaterThanToken, OperatorKind.GreaterThanOrEqual => SyntaxKind.GreaterThanEqualsToken, OperatorKind.Increment => SyntaxKind.PlusPlusToken, OperatorKind.Inequality => SyntaxKind.ExclamationEqualsToken, OperatorKind.LeftShift => SyntaxKind.LessThanLessThanToken, OperatorKind.LessThan => SyntaxKind.LessThanToken, OperatorKind.LessThanOrEqual => SyntaxKind.LessThanEqualsToken, OperatorKind.LogicalNot => SyntaxKind.ExclamationToken, OperatorKind.Modulus => SyntaxKind.PercentToken, OperatorKind.Multiply => SyntaxKind.AsteriskToken, OperatorKind.OnesComplement => SyntaxKind.TildeToken, OperatorKind.RightShift => SyntaxKind.GreaterThanGreaterThanToken, OperatorKind.Subtraction => SyntaxKind.MinusToken, OperatorKind.True => SyntaxKind.TrueKeyword, OperatorKind.UnaryNegation => SyntaxKind.MinusToken, OperatorKind.UnaryPlus => SyntaxKind.PlusToken, _ => throw new ArgumentException("Unknown operator kind."), }; private static ParameterListSyntax AsParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.ParameterList(); } public override SyntaxNode ConstructorDeclaration( string name, IEnumerable<SyntaxNode> parameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> baseConstructorArguments, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.ConstructorDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ConstructorDeclaration), (name ?? "ctor").ToIdentifierToken(), AsParameterList(parameters), baseConstructorArguments != null ? SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(baseConstructorArguments.Select(AsArgument)))) : null, CreateBlock(statements)); } public override SyntaxNode PropertyDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } if (hasGetter) accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); if (hasSetter) accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.PropertyDeclaration( attributeLists: default, AsModifierList(accessibility, actualModifiers, SyntaxKind.PropertyDeclaration), (TypeSyntax)type, explicitInterfaceSpecifier: null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode GetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, accessibility, statements); public override SyntaxNode SetAccessorDeclaration(Accessibility accessibility, IEnumerable<SyntaxNode> statements) => AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, accessibility, statements); private static SyntaxNode AccessorDeclaration( SyntaxKind kind, Accessibility accessibility, IEnumerable<SyntaxNode> statements) { var accessor = SyntaxFactory.AccessorDeclaration(kind); accessor = accessor.WithModifiers( AsModifierList(accessibility, DeclarationModifiers.None, SyntaxKind.PropertyDeclaration)); accessor = statements == null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) : accessor.WithBody(CreateBlock(statements)); return accessor; } public override SyntaxNode WithAccessorDeclarations(SyntaxNode declaration, IEnumerable<SyntaxNode> accessorDeclarations) => declaration switch { PropertyDeclarationSyntax property => property.WithAccessorList(CreateAccessorList(property.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), IndexerDeclarationSyntax indexer => indexer.WithAccessorList(CreateAccessorList(indexer.AccessorList, accessorDeclarations)) .WithExpressionBody(null) .WithSemicolonToken(default), _ => declaration, }; private static AccessorListSyntax CreateAccessorList(AccessorListSyntax accessorListOpt, IEnumerable<SyntaxNode> accessorDeclarations) { var list = SyntaxFactory.List(accessorDeclarations.Cast<AccessorDeclarationSyntax>()); return accessorListOpt == null ? SyntaxFactory.AccessorList(list) : accessorListOpt.WithAccessors(list); } public override SyntaxNode IndexerDeclaration( IEnumerable<SyntaxNode> parameters, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> getAccessorStatements, IEnumerable<SyntaxNode> setAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); var hasGetter = !modifiers.IsWriteOnly; var hasSetter = !modifiers.IsReadOnly; if (modifiers.IsAbstract) { getAccessorStatements = null; setAccessorStatements = null; } else { if (getAccessorStatements == null && hasGetter) { getAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (setAccessorStatements == null && hasSetter) { setAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } if (hasGetter) { accessors.Add(AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getAccessorStatements)); } if (hasSetter) { accessors.Add(AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setAccessorStatements)); } var actualModifiers = modifiers - (DeclarationModifiers.ReadOnly | DeclarationModifiers.WriteOnly); return SyntaxFactory.IndexerDeclaration( default, AsModifierList(accessibility, actualModifiers, SyntaxKind.IndexerDeclaration), (TypeSyntax)type, null, AsBracketedParameterList(parameters), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } private static BracketedParameterListSyntax AsBracketedParameterList(IEnumerable<SyntaxNode> parameters) { return parameters != null ? SyntaxFactory.BracketedParameterList(SyntaxFactory.SeparatedList(parameters.Cast<ParameterSyntax>())) : SyntaxFactory.BracketedParameterList(); } private static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var ad = SyntaxFactory.AccessorDeclaration( kind, statements != null ? CreateBlock(statements) : null); if (statements == null) { ad = ad.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return ad; } public override SyntaxNode EventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers) { return SyntaxFactory.EventFieldDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventFieldDeclaration), SyntaxFactory.VariableDeclaration( (TypeSyntax)type, SyntaxFactory.SingletonSeparatedList( SyntaxFactory.VariableDeclarator(name)))); } public override SyntaxNode CustomEventDeclaration( string name, SyntaxNode type, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> parameters, IEnumerable<SyntaxNode> addAccessorStatements, IEnumerable<SyntaxNode> removeAccessorStatements) { var accessors = new List<AccessorDeclarationSyntax>(); if (modifiers.IsAbstract) { addAccessorStatements = null; removeAccessorStatements = null; } else { if (addAccessorStatements == null) { addAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } if (removeAccessorStatements == null) { removeAccessorStatements = SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } } accessors.Add(AccessorDeclaration(SyntaxKind.AddAccessorDeclaration, addAccessorStatements)); accessors.Add(AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, removeAccessorStatements)); return SyntaxFactory.EventDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EventDeclaration), (TypeSyntax)type, null, name.ToIdentifierToken(), SyntaxFactory.AccessorList(SyntaxFactory.List(accessors))); } public override SyntaxNode AsPublicInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { // C# interface implementations are implicit/not-specified -- so they are just named the name as the interface member return PreserveTrivia(declaration, d => { d = WithInterfaceSpecifier(d, null); d = this.AsImplementation(d, Accessibility.Public); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return d; }); } public override SyntaxNode AsPrivateInterfaceImplementation(SyntaxNode declaration, SyntaxNode interfaceTypeName, string interfaceMemberName) { return PreserveTrivia(declaration, d => { d = this.AsImplementation(d, Accessibility.NotApplicable); d = this.WithoutConstraints(d); if (interfaceMemberName != null) { d = this.WithName(d, interfaceMemberName); } return WithInterfaceSpecifier(d, SyntaxFactory.ExplicitInterfaceSpecifier((NameSyntax)interfaceTypeName)); }); } private SyntaxNode WithoutConstraints(SyntaxNode declaration) { if (declaration.IsKind(SyntaxKind.MethodDeclaration, out MethodDeclarationSyntax method)) { if (method.ConstraintClauses.Count > 0) { return this.RemoveNodes(method, method.ConstraintClauses); } } return declaration; } private static SyntaxNode WithInterfaceSpecifier(SyntaxNode declaration, ExplicitInterfaceSpecifierSyntax specifier) => declaration.Kind() switch { SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithExplicitInterfaceSpecifier(specifier), _ => declaration, }; private SyntaxNode AsImplementation(SyntaxNode declaration, Accessibility requiredAccess) { declaration = this.WithAccessibility(declaration, requiredAccess); declaration = this.WithModifiers(declaration, this.GetModifiers(declaration) - DeclarationModifiers.Abstract); declaration = WithBodies(declaration); return declaration; } private static SyntaxNode WithBodies(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; return method.Body == null ? method.WithSemicolonToken(default).WithBody(CreateBlock(null)) : method; case SyntaxKind.OperatorDeclaration: var op = (OperatorDeclarationSyntax)declaration; return op.Body == null ? op.WithSemicolonToken(default).WithBody(CreateBlock(null)) : op; case SyntaxKind.ConversionOperatorDeclaration: var cop = (ConversionOperatorDeclarationSyntax)declaration; return cop.Body == null ? cop.WithSemicolonToken(default).WithBody(CreateBlock(null)) : cop; case SyntaxKind.PropertyDeclaration: var prop = (PropertyDeclarationSyntax)declaration; return prop.WithAccessorList(WithBodies(prop.AccessorList)); case SyntaxKind.IndexerDeclaration: var ind = (IndexerDeclarationSyntax)declaration; return ind.WithAccessorList(WithBodies(ind.AccessorList)); case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)declaration; return ev.WithAccessorList(WithBodies(ev.AccessorList)); } return declaration; } private static AccessorListSyntax WithBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(x => WithBody(x)))); private static AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax accessor) { if (accessor.Body == null) { return accessor.WithSemicolonToken(default).WithBody(CreateBlock(null)); } else { return accessor; } } private static AccessorListSyntax WithoutBodies(AccessorListSyntax accessorList) => accessorList.WithAccessors(SyntaxFactory.List(accessorList.Accessors.Select(WithoutBody))); private static AccessorDeclarationSyntax WithoutBody(AccessorDeclarationSyntax accessor) => accessor.Body != null ? accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithBody(null) : accessor; public override SyntaxNode ClassDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, SyntaxNode baseType, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { List<BaseTypeSyntax> baseTypes = null; if (baseType != null || interfaceTypes != null) { baseTypes = new List<BaseTypeSyntax>(); if (baseType != null) { baseTypes.Add(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)); } if (interfaceTypes != null) { baseTypes.AddRange(interfaceTypes.Select(i => SyntaxFactory.SimpleBaseType((TypeSyntax)i))); } if (baseTypes.Count == 0) { baseTypes = null; } } return SyntaxFactory.ClassDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.ClassDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), baseTypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(baseTypes)) : null, default, this.AsClassMembers(name, members)); } private SyntaxList<MemberDeclarationSyntax> AsClassMembers(string className, IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(m => this.AsClassMember(m, className)).Where(m => m != null)) : default; } private MemberDeclarationSyntax AsClassMember(SyntaxNode node, string className) { switch (node.Kind()) { case SyntaxKind.ConstructorDeclaration: node = ((ConstructorDeclarationSyntax)node).WithIdentifier(className.ToIdentifierToken()); break; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: node = this.AsIsolatedDeclaration(node); break; } return node as MemberDeclarationSyntax; } public override SyntaxNode StructDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> interfaceTypes, IEnumerable<SyntaxNode> members) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.StructDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.StructDeclaration), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsClassMembers(name, members)); } public override SyntaxNode InterfaceDeclaration( string name, IEnumerable<string> typeParameters, Accessibility accessibility, IEnumerable<SyntaxNode> interfaceTypes = null, IEnumerable<SyntaxNode> members = null) { var itypes = interfaceTypes?.Select(i => (BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)i)).ToList(); if (itypes?.Count == 0) { itypes = null; } return SyntaxFactory.InterfaceDeclaration( default, AsModifierList(accessibility, DeclarationModifiers.None), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), itypes != null ? SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(itypes)) : null, default, this.AsInterfaceMembers(members)); } private SyntaxList<MemberDeclarationSyntax> AsInterfaceMembers(IEnumerable<SyntaxNode> members) { return members != null ? SyntaxFactory.List(members.Select(this.AsInterfaceMember).OfType<MemberDeclarationSyntax>()) : default; } internal override SyntaxNode AsInterfaceMember(SyntaxNode m) { return this.Isolate(m, member => { Accessibility acc; DeclarationModifiers modifiers; switch (member.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)member) .WithModifiers(default) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)) .WithBody(null); case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)member; return property .WithModifiers(default) .WithAccessorList(WithoutBodies(property.AccessorList)); case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)member; return indexer .WithModifiers(default) .WithAccessorList(WithoutBodies(indexer.AccessorList)); // convert event into field event case SyntaxKind.EventDeclaration: var ev = (EventDeclarationSyntax)member; return this.EventDeclaration( ev.Identifier.ValueText, ev.Type, Accessibility.NotApplicable, DeclarationModifiers.None); case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)member; return ef.WithModifiers(default); // convert field into property case SyntaxKind.FieldDeclaration: var f = (FieldDeclarationSyntax)member; SyntaxFacts.GetAccessibilityAndModifiers(f.Modifiers, out acc, out modifiers, out _); return this.AsInterfaceMember( this.PropertyDeclaration(this.GetName(f), this.ClearTrivia(this.GetType(f)), acc, modifiers, getAccessorStatements: null, setAccessorStatements: null)); default: return null; } }); } public override SyntaxNode EnumDeclaration( string name, Accessibility accessibility, DeclarationModifiers modifiers, IEnumerable<SyntaxNode> members) { return EnumDeclaration(name, underlyingType: null, accessibility, modifiers, members); } internal override SyntaxNode EnumDeclaration(string name, SyntaxNode underlyingType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default, IEnumerable<SyntaxNode> members = null) { return SyntaxFactory.EnumDeclaration( default, AsModifierList(accessibility, modifiers, SyntaxKind.EnumDeclaration), name.ToIdentifierToken(), underlyingType != null ? SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList((BaseTypeSyntax)SyntaxFactory.SimpleBaseType((TypeSyntax)underlyingType))) : null, this.AsEnumMembers(members)); } public override SyntaxNode EnumMember(string name, SyntaxNode expression) { return SyntaxFactory.EnumMemberDeclaration( default, name.ToIdentifierToken(), expression != null ? SyntaxFactory.EqualsValueClause((ExpressionSyntax)expression) : null); } private EnumMemberDeclarationSyntax AsEnumMember(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.IdentifierName: var id = (IdentifierNameSyntax)node; return (EnumMemberDeclarationSyntax)this.EnumMember(id.Identifier.ToString(), null); case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)node; if (fd.Declaration.Variables.Count == 1) { var vd = fd.Declaration.Variables[0]; return (EnumMemberDeclarationSyntax)this.EnumMember(vd.Identifier.ToString(), vd.Initializer?.Value); } break; } return (EnumMemberDeclarationSyntax)node; } private SeparatedSyntaxList<EnumMemberDeclarationSyntax> AsEnumMembers(IEnumerable<SyntaxNode> members) => members != null ? SyntaxFactory.SeparatedList(members.Select(this.AsEnumMember)) : default; public override SyntaxNode DelegateDeclaration( string name, IEnumerable<SyntaxNode> parameters, IEnumerable<string> typeParameters, SyntaxNode returnType, Accessibility accessibility = Accessibility.NotApplicable, DeclarationModifiers modifiers = default) { return SyntaxFactory.DelegateDeclaration( default, AsModifierList(accessibility, modifiers), returnType != null ? (TypeSyntax)returnType : SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), name.ToIdentifierToken(), AsTypeParameterList(typeParameters), AsParameterList(parameters), default); } public override SyntaxNode Attribute(SyntaxNode name, IEnumerable<SyntaxNode> attributeArguments) => AsAttributeList(SyntaxFactory.Attribute((NameSyntax)name, AsAttributeArgumentList(attributeArguments))); public override SyntaxNode AttributeArgument(string name, SyntaxNode expression) { return name != null ? SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(name.ToIdentifierName()), null, (ExpressionSyntax)expression) : SyntaxFactory.AttributeArgument((ExpressionSyntax)expression); } private static AttributeArgumentListSyntax AsAttributeArgumentList(IEnumerable<SyntaxNode> arguments) { if (arguments != null) { return SyntaxFactory.AttributeArgumentList(SyntaxFactory.SeparatedList(arguments.Select(AsAttributeArgument))); } else { return null; } } private static AttributeArgumentSyntax AsAttributeArgument(SyntaxNode node) { if (node is ExpressionSyntax expr) { return SyntaxFactory.AttributeArgument(expr); } if (node is ArgumentSyntax arg && arg.Expression != null) { return SyntaxFactory.AttributeArgument(null, arg.NameColon, arg.Expression); } return (AttributeArgumentSyntax)node; } public override TNode ClearTrivia<TNode>(TNode node) { if (node != null) { return node.WithLeadingTrivia(SyntaxFactory.ElasticMarker) .WithTrailingTrivia(SyntaxFactory.ElasticMarker); } else { return null; } } private static SyntaxList<AttributeListSyntax> AsAttributeLists(IEnumerable<SyntaxNode> attributes) { if (attributes != null) { return SyntaxFactory.List(attributes.Select(AsAttributeList)); } else { return default; } } private static AttributeListSyntax AsAttributeList(SyntaxNode node) { if (node is AttributeSyntax attr) { return SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(attr)); } else { return (AttributeListSyntax)node; } } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declAttributes = new(); public override IReadOnlyList<SyntaxNode> GetAttributes(SyntaxNode declaration) { if (!s_declAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => !IsReturnAttribute(al)))); } return attrs; } private static readonly ConditionalWeakTable<SyntaxNode, IReadOnlyList<SyntaxNode>> s_declReturnAttributes = new(); public override IReadOnlyList<SyntaxNode> GetReturnAttributes(SyntaxNode declaration) { if (!s_declReturnAttributes.TryGetValue(declaration, out var attrs)) { attrs = s_declReturnAttributes.GetValue(declaration, declaration => Flatten(declaration.GetAttributeLists().Where(al => IsReturnAttribute(al)))); } return attrs; } private static bool IsReturnAttribute(AttributeListSyntax list) => list.Target?.Identifier.IsKind(SyntaxKind.ReturnKeyword) ?? false; public override SyntaxNode InsertAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) => this.Isolate(declaration, d => this.InsertAttributesInternal(d, index, attributes)); private SyntaxNode InsertAttributesInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsAttributeLists(attributes); var existingAttributes = this.GetAttributes(declaration); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(declaration, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(declaration, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = declaration.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(declaration, newList); } } public override SyntaxNode InsertReturnAttributes(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributes) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.DelegateDeclaration: return this.Isolate(declaration, d => this.InsertReturnAttributesInternal(d, index, attributes)); default: return declaration; } } private SyntaxNode InsertReturnAttributesInternal(SyntaxNode d, int index, IEnumerable<SyntaxNode> attributes) { var newAttributes = AsReturnAttributes(attributes); var existingAttributes = this.GetReturnAttributes(d); if (index >= 0 && index < existingAttributes.Count) { return this.InsertNodesBefore(d, existingAttributes[index], newAttributes); } else if (existingAttributes.Count > 0) { return this.InsertNodesAfter(d, existingAttributes[existingAttributes.Count - 1], newAttributes); } else { var lists = d.GetAttributeLists(); var newList = lists.AddRange(newAttributes); return WithAttributeLists(d, newList); } } private static IEnumerable<AttributeListSyntax> AsReturnAttributes(IEnumerable<SyntaxNode> attributes) { return AsAttributeLists(attributes) .Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.ReturnKeyword)))); } private static SyntaxList<AttributeListSyntax> AsAssemblyAttributes(IEnumerable<AttributeListSyntax> attributes) { return SyntaxFactory.List( attributes.Select(list => list.WithTarget(SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword))))); } public override IReadOnlyList<SyntaxNode> GetAttributeArguments(SyntaxNode attributeDeclaration) { switch (attributeDeclaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)attributeDeclaration; if (list.Attributes.Count == 1) { return this.GetAttributeArguments(list.Attributes[0]); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)attributeDeclaration; if (attr.ArgumentList != null) { return attr.ArgumentList.Arguments; } break; } return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertAttributeArguments(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) => this.Isolate(declaration, d => InsertAttributeArgumentsInternal(d, index, attributeArguments)); private static SyntaxNode InsertAttributeArgumentsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> attributeArguments) { var newArgumentList = AsAttributeArgumentList(attributeArguments); var existingArgumentList = GetAttributeArgumentList(declaration); if (existingArgumentList == null) { return WithAttributeArgumentList(declaration, newArgumentList); } else if (newArgumentList != null) { return WithAttributeArgumentList(declaration, existingArgumentList.WithArguments(existingArgumentList.Arguments.InsertRange(index, newArgumentList.Arguments))); } else { return declaration; } } private static AttributeArgumentListSyntax GetAttributeArgumentList(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return list.Attributes[0].ArgumentList; } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.ArgumentList; } return null; } private static SyntaxNode WithAttributeArgumentList(SyntaxNode declaration, AttributeArgumentListSyntax argList) { switch (declaration.Kind()) { case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return ReplaceWithTrivia(declaration, list.Attributes[0], list.Attributes[0].WithArgumentList(argList)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; return attr.WithArgumentList(argList); } return declaration; } internal static SyntaxList<AttributeListSyntax> GetAttributeLists(SyntaxNode declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, StatementSyntax statement => statement.AttributeLists, _ => default, }; private static SyntaxNode WithAttributeLists(SyntaxNode declaration, SyntaxList<AttributeListSyntax> attributeLists) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithAttributeLists(attributeLists), AccessorDeclarationSyntax accessor => accessor.WithAttributeLists(attributeLists), ParameterSyntax parameter => parameter.WithAttributeLists(attributeLists), CompilationUnitSyntax compilationUnit => compilationUnit.WithAttributeLists(AsAssemblyAttributes(attributeLists)), StatementSyntax statement => statement.WithAttributeLists(attributeLists), _ => declaration, }; internal override ImmutableArray<SyntaxNode> GetTypeInheritance(SyntaxNode declaration) => declaration is BaseTypeDeclarationSyntax baseType && baseType.BaseList != null ? ImmutableArray.Create<SyntaxNode>(baseType.BaseList) : ImmutableArray<SyntaxNode>.Empty; public override IReadOnlyList<SyntaxNode> GetNamespaceImports(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.Usings, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Usings, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode InsertNamespaceImports(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) => PreserveTrivia(declaration, d => this.InsertNamespaceImportsInternal(d, index, imports)); private SyntaxNode InsertNamespaceImportsInternal(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> imports) { var usingsToInsert = this.AsUsingDirectives(imports); return declaration switch { CompilationUnitSyntax cu => cu.WithUsings(cu.Usings.InsertRange(index, usingsToInsert)), BaseNamespaceDeclarationSyntax nd => nd.WithUsings(nd.Usings.InsertRange(index, usingsToInsert)), _ => declaration, }; } public override IReadOnlyList<SyntaxNode> GetMembers(SyntaxNode declaration) => Flatten(declaration switch { TypeDeclarationSyntax type => type.Members, EnumDeclarationSyntax @enum => @enum.Members, BaseNamespaceDeclarationSyntax @namespace => @namespace.Members, CompilationUnitSyntax compilationUnit => compilationUnit.Members, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }); private static ImmutableArray<SyntaxNode> Flatten(IEnumerable<SyntaxNode> declarations) { var builder = ArrayBuilder<SyntaxNode>.GetInstance(); foreach (var declaration in declarations) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: FlattenDeclaration(builder, declaration, ((FieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.EventFieldDeclaration: FlattenDeclaration(builder, declaration, ((EventFieldDeclarationSyntax)declaration).Declaration); break; case SyntaxKind.LocalDeclarationStatement: FlattenDeclaration(builder, declaration, ((LocalDeclarationStatementSyntax)declaration).Declaration); break; case SyntaxKind.VariableDeclaration: FlattenDeclaration(builder, declaration, (VariableDeclarationSyntax)declaration); break; case SyntaxKind.AttributeList: var attrList = (AttributeListSyntax)declaration; if (attrList.Attributes.Count > 1) { builder.AddRange(attrList.Attributes); } else { builder.Add(attrList); } break; default: builder.Add(declaration); break; } } return builder.ToImmutableAndFree(); static void FlattenDeclaration(ArrayBuilder<SyntaxNode> builder, SyntaxNode declaration, VariableDeclarationSyntax variableDeclaration) { if (variableDeclaration.Variables.Count > 1) { builder.AddRange(variableDeclaration.Variables); } else { builder.Add(declaration); } } } private static int GetDeclarationCount(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables.Count, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables.Count, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables.Count, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes.Count, _ => 1, }; private static SyntaxNode EnsureRecordDeclarationHasBody(SyntaxNode declaration) { if (declaration is RecordDeclarationSyntax recordDeclaration) { return recordDeclaration .WithSemicolonToken(default) .WithOpenBraceToken(recordDeclaration.OpenBraceToken == default ? SyntaxFactory.Token(SyntaxKind.OpenBraceToken) : recordDeclaration.OpenBraceToken) .WithCloseBraceToken(recordDeclaration.CloseBraceToken == default ? SyntaxFactory.Token(SyntaxKind.CloseBraceToken) : recordDeclaration.CloseBraceToken); } return declaration; } public override SyntaxNode InsertMembers(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> members) { declaration = EnsureRecordDeclarationHasBody(declaration); var newMembers = this.AsMembersOf(declaration, members); var existingMembers = this.GetMembers(declaration); if (index >= 0 && index < existingMembers.Count) { return this.InsertNodesBefore(declaration, existingMembers[index], newMembers); } else if (existingMembers.Count > 0) { return this.InsertNodesAfter(declaration, existingMembers[existingMembers.Count - 1], newMembers); } else { return declaration switch { TypeDeclarationSyntax type => type.WithMembers(type.Members.AddRange(newMembers)), EnumDeclarationSyntax @enum => @enum.WithMembers(@enum.Members.AddRange(newMembers.OfType<EnumMemberDeclarationSyntax>())), BaseNamespaceDeclarationSyntax @namespace => @namespace.WithMembers(@namespace.Members.AddRange(newMembers)), CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(compilationUnit.Members.AddRange(newMembers)), _ => declaration, }; } } private IEnumerable<MemberDeclarationSyntax> AsMembersOf(SyntaxNode declaration, IEnumerable<SyntaxNode> members) => members?.Select(m => this.AsMemberOf(declaration, m)).OfType<MemberDeclarationSyntax>(); private SyntaxNode AsMemberOf(SyntaxNode declaration, SyntaxNode member) => declaration switch { InterfaceDeclarationSyntax => this.AsInterfaceMember(member), TypeDeclarationSyntax typeDeclaration => this.AsClassMember(member, typeDeclaration.Identifier.Text), EnumDeclarationSyntax => this.AsEnumMember(member), BaseNamespaceDeclarationSyntax => AsNamespaceMember(member), CompilationUnitSyntax => AsNamespaceMember(member), _ => null, }; public override Accessibility GetAccessibility(SyntaxNode declaration) => SyntaxFacts.GetAccessibility(declaration); public override SyntaxNode WithAccessibility(SyntaxNode declaration, Accessibility accessibility) { if (!SyntaxFacts.CanHaveAccessibility(declaration) && accessibility != Accessibility.NotApplicable) { return declaration; } return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out _, out var modifiers, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } private static readonly DeclarationModifiers s_fieldModifiers = DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.Volatile; private static readonly DeclarationModifiers s_methodModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_constructorModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_destructorModifiers = DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_propertyModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_eventFieldModifiers = DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_indexerModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.Extern | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_classModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_recordModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_structModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Ref | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_interfaceModifiers = DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; private static readonly DeclarationModifiers s_accessorModifiers = DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual; private static readonly DeclarationModifiers s_localFunctionModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static | DeclarationModifiers.Extern; private static readonly DeclarationModifiers s_lambdaModifiers = DeclarationModifiers.Async | DeclarationModifiers.Static; private static DeclarationModifiers GetAllowedModifiers(SyntaxKind kind) { switch (kind) { case SyntaxKind.RecordDeclaration: return s_recordModifiers; case SyntaxKind.ClassDeclaration: return s_classModifiers; case SyntaxKind.EnumDeclaration: return DeclarationModifiers.New; case SyntaxKind.DelegateDeclaration: return DeclarationModifiers.New | DeclarationModifiers.Unsafe; case SyntaxKind.InterfaceDeclaration: return s_interfaceModifiers; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return s_structModifiers; case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return s_methodModifiers; case SyntaxKind.ConstructorDeclaration: return s_constructorModifiers; case SyntaxKind.DestructorDeclaration: return s_destructorModifiers; case SyntaxKind.FieldDeclaration: return s_fieldModifiers; case SyntaxKind.PropertyDeclaration: return s_propertyModifiers; case SyntaxKind.IndexerDeclaration: return s_indexerModifiers; case SyntaxKind.EventFieldDeclaration: return s_eventFieldModifiers; case SyntaxKind.EventDeclaration: return s_eventModifiers; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return s_accessorModifiers; case SyntaxKind.LocalFunctionStatement: return s_localFunctionModifiers; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return s_lambdaModifiers; case SyntaxKind.EnumMemberDeclaration: case SyntaxKind.Parameter: case SyntaxKind.LocalDeclarationStatement: default: return DeclarationModifiers.None; } } public override DeclarationModifiers GetModifiers(SyntaxNode declaration) { var modifierTokens = SyntaxFacts.GetModifierTokens(declaration); SyntaxFacts.GetAccessibilityAndModifiers(modifierTokens, out _, out var modifiers, out _); return modifiers; } public override SyntaxNode WithModifiers(SyntaxNode declaration, DeclarationModifiers modifiers) => this.Isolate(declaration, d => this.WithModifiersInternal(d, modifiers)); private SyntaxNode WithModifiersInternal(SyntaxNode declaration, DeclarationModifiers modifiers) { modifiers &= GetAllowedModifiers(declaration.Kind()); var existingModifiers = this.GetModifiers(declaration); if (modifiers != existingModifiers) { return this.Isolate(declaration, d => { var tokens = SyntaxFacts.GetModifierTokens(d); SyntaxFacts.GetAccessibilityAndModifiers(tokens, out var accessibility, out var tmp, out _); var newTokens = Merge(tokens, AsModifierList(accessibility, modifiers)); return SetModifierTokens(d, newTokens); }); } else { // no change return declaration; } } private static SyntaxNode SetModifierTokens(SyntaxNode declaration, SyntaxTokenList modifiers) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.WithModifiers(modifiers), ParameterSyntax parameter => parameter.WithModifiers(modifiers), LocalDeclarationStatementSyntax localDecl => localDecl.WithModifiers(modifiers), LocalFunctionStatementSyntax localFunc => localFunc.WithModifiers(modifiers), AccessorDeclarationSyntax accessor => accessor.WithModifiers(modifiers), AnonymousFunctionExpressionSyntax anonymous => anonymous.WithModifiers(modifiers), _ => declaration, }; private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers, SyntaxKind kind) => AsModifierList(accessibility, GetAllowedModifiers(kind) & modifiers); private static SyntaxTokenList AsModifierList(Accessibility accessibility, DeclarationModifiers modifiers) { using var _ = ArrayBuilder<SyntaxToken>.GetInstance(out var list); switch (accessibility) { case Accessibility.Internal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); break; case Accessibility.Public: list.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)); break; case Accessibility.Private: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); break; case Accessibility.Protected: list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedOrInternal: list.Add(SyntaxFactory.Token(SyntaxKind.InternalKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.ProtectedAndInternal: list.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)); list.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)); break; case Accessibility.NotApplicable: break; } if (modifiers.IsAbstract) list.Add(SyntaxFactory.Token(SyntaxKind.AbstractKeyword)); if (modifiers.IsNew) list.Add(SyntaxFactory.Token(SyntaxKind.NewKeyword)); if (modifiers.IsSealed) list.Add(SyntaxFactory.Token(SyntaxKind.SealedKeyword)); if (modifiers.IsOverride) list.Add(SyntaxFactory.Token(SyntaxKind.OverrideKeyword)); if (modifiers.IsVirtual) list.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword)); if (modifiers.IsStatic) list.Add(SyntaxFactory.Token(SyntaxKind.StaticKeyword)); if (modifiers.IsAsync) list.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword)); if (modifiers.IsConst) list.Add(SyntaxFactory.Token(SyntaxKind.ConstKeyword)); if (modifiers.IsReadOnly) list.Add(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)); if (modifiers.IsUnsafe) list.Add(SyntaxFactory.Token(SyntaxKind.UnsafeKeyword)); if (modifiers.IsVolatile) list.Add(SyntaxFactory.Token(SyntaxKind.VolatileKeyword)); if (modifiers.IsExtern) list.Add(SyntaxFactory.Token(SyntaxKind.ExternKeyword)); // partial and ref must be last if (modifiers.IsRef) list.Add(SyntaxFactory.Token(SyntaxKind.RefKeyword)); if (modifiers.IsPartial) list.Add(SyntaxFactory.Token(SyntaxKind.PartialKeyword)); return SyntaxFactory.TokenList(list); } private static TypeParameterListSyntax AsTypeParameterList(IEnumerable<string> typeParameterNames) { var typeParameters = typeParameterNames != null ? SyntaxFactory.TypeParameterList(SyntaxFactory.SeparatedList(typeParameterNames.Select(name => SyntaxFactory.TypeParameter(name)))) : null; if (typeParameters != null && typeParameters.Parameters.Count == 0) { typeParameters = null; } return typeParameters; } public override SyntaxNode WithTypeParameters(SyntaxNode declaration, IEnumerable<string> typeParameterNames) { var typeParameters = AsTypeParameterList(typeParameterNames); return declaration switch { MethodDeclarationSyntax method => method.WithTypeParameterList(typeParameters), TypeDeclarationSyntax type => type.WithTypeParameterList(typeParameters), DelegateDeclarationSyntax @delegate => @delegate.WithTypeParameterList(typeParameters), _ => declaration, }; } internal override SyntaxNode WithExplicitInterfaceImplementations(SyntaxNode declaration, ImmutableArray<ISymbol> explicitInterfaceImplementations) => WithAccessibility(declaration switch { MethodDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), PropertyDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), EventDeclarationSyntax member => member.WithExplicitInterfaceSpecifier(CreateExplicitInterfaceSpecifier(explicitInterfaceImplementations)), _ => declaration, }, Accessibility.NotApplicable); private static ExplicitInterfaceSpecifierSyntax CreateExplicitInterfaceSpecifier(ImmutableArray<ISymbol> explicitInterfaceImplementations) => SyntaxFactory.ExplicitInterfaceSpecifier(explicitInterfaceImplementations[0].ContainingType.GenerateNameSyntax()); public override SyntaxNode WithTypeConstraint(SyntaxNode declaration, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) => declaration switch { MethodDeclarationSyntax method => method.WithConstraintClauses(WithTypeConstraints(method.ConstraintClauses, typeParameterName, kinds, types)), TypeDeclarationSyntax type => type.WithConstraintClauses(WithTypeConstraints(type.ConstraintClauses, typeParameterName, kinds, types)), DelegateDeclarationSyntax @delegate => @delegate.WithConstraintClauses(WithTypeConstraints(@delegate.ConstraintClauses, typeParameterName, kinds, types)), _ => declaration, }; private static SyntaxList<TypeParameterConstraintClauseSyntax> WithTypeConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> clauses, string typeParameterName, SpecialTypeConstraintKind kinds, IEnumerable<SyntaxNode> types) { var constraints = types != null ? SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(types.Select(t => SyntaxFactory.TypeConstraint((TypeSyntax)t))) : SyntaxFactory.SeparatedList<TypeParameterConstraintSyntax>(); if ((kinds & SpecialTypeConstraintKind.Constructor) != 0) { constraints = constraints.Add(SyntaxFactory.ConstructorConstraint()); } var isReferenceType = (kinds & SpecialTypeConstraintKind.ReferenceType) != 0; var isValueType = (kinds & SpecialTypeConstraintKind.ValueType) != 0; if (isReferenceType || isValueType) { constraints = constraints.Insert(0, SyntaxFactory.ClassOrStructConstraint(isReferenceType ? SyntaxKind.ClassConstraint : SyntaxKind.StructConstraint)); } var clause = clauses.FirstOrDefault(c => c.Name.Identifier.ToString() == typeParameterName); if (clause == null) { if (constraints.Count > 0) { return clauses.Add(SyntaxFactory.TypeParameterConstraintClause(typeParameterName.ToIdentifierName(), constraints)); } else { return clauses; } } else if (constraints.Count == 0) { return clauses.Remove(clause); } else { return clauses.Replace(clause, clause.WithConstraints(constraints)); } } public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) => SyntaxFacts.GetDeclarationKind(declaration); public override string GetName(SyntaxNode declaration) => declaration switch { BaseTypeDeclarationSyntax baseTypeDeclaration => baseTypeDeclaration.Identifier.ValueText, DelegateDeclarationSyntax delegateDeclaration => delegateDeclaration.Identifier.ValueText, MethodDeclarationSyntax methodDeclaration => methodDeclaration.Identifier.ValueText, BaseFieldDeclarationSyntax baseFieldDeclaration => this.GetName(baseFieldDeclaration.Declaration), PropertyDeclarationSyntax propertyDeclaration => propertyDeclaration.Identifier.ValueText, EnumMemberDeclarationSyntax enumMemberDeclaration => enumMemberDeclaration.Identifier.ValueText, EventDeclarationSyntax eventDeclaration => eventDeclaration.Identifier.ValueText, BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.Name.ToString(), UsingDirectiveSyntax usingDirective => usingDirective.Name.ToString(), ParameterSyntax parameter => parameter.Identifier.ValueText, LocalDeclarationStatementSyntax localDeclaration => this.GetName(localDeclaration.Declaration), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => variableDeclaration.Variables[0].Identifier.ValueText, VariableDeclaratorSyntax variableDeclarator => variableDeclarator.Identifier.ValueText, TypeParameterSyntax typeParameter => typeParameter.Identifier.ValueText, AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => attributeList.Attributes[0].Name.ToString(), AttributeSyntax attribute => attribute.Name.ToString(), _ => string.Empty }; public override SyntaxNode WithName(SyntaxNode declaration, string name) => this.Isolate(declaration, d => this.WithNameInternal(d, name)); private SyntaxNode WithNameInternal(SyntaxNode declaration, string name) { var id = name.ToIdentifierToken(); return declaration switch { BaseTypeDeclarationSyntax typeDeclaration => ReplaceWithTrivia(declaration, typeDeclaration.Identifier, id), DelegateDeclarationSyntax delegateDeclaration => ReplaceWithTrivia(declaration, delegateDeclaration.Identifier, id), MethodDeclarationSyntax methodDeclaration => ReplaceWithTrivia(declaration, methodDeclaration.Identifier, id), BaseFieldDeclarationSyntax fieldDeclaration when fieldDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, fieldDeclaration.Declaration.Variables[0].Identifier, id), PropertyDeclarationSyntax propertyDeclaration => ReplaceWithTrivia(declaration, propertyDeclaration.Identifier, id), EnumMemberDeclarationSyntax enumMemberDeclaration => ReplaceWithTrivia(declaration, enumMemberDeclaration.Identifier, id), EventDeclarationSyntax eventDeclaration => ReplaceWithTrivia(declaration, eventDeclaration.Identifier, id), BaseNamespaceDeclarationSyntax namespaceDeclaration => ReplaceWithTrivia(declaration, namespaceDeclaration.Name, this.DottedName(name)), UsingDirectiveSyntax usingDeclaration => ReplaceWithTrivia(declaration, usingDeclaration.Name, this.DottedName(name)), ParameterSyntax parameter => ReplaceWithTrivia(declaration, parameter.Identifier, id), LocalDeclarationStatementSyntax localDeclaration when localDeclaration.Declaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, localDeclaration.Declaration.Variables[0].Identifier, id), TypeParameterSyntax typeParameter => ReplaceWithTrivia(declaration, typeParameter.Identifier, id), AttributeListSyntax attributeList when attributeList.Attributes.Count == 1 => ReplaceWithTrivia(declaration, attributeList.Attributes[0].Name, this.DottedName(name)), AttributeSyntax attribute => ReplaceWithTrivia(declaration, attribute.Name, this.DottedName(name)), VariableDeclarationSyntax variableDeclaration when variableDeclaration.Variables.Count == 1 => ReplaceWithTrivia(declaration, variableDeclaration.Variables[0].Identifier, id), VariableDeclaratorSyntax variableDeclarator => ReplaceWithTrivia(declaration, variableDeclarator.Identifier, id), _ => declaration }; } public override SyntaxNode GetType(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return NotVoid(((DelegateDeclarationSyntax)declaration).ReturnType); case SyntaxKind.MethodDeclaration: return NotVoid(((MethodDeclarationSyntax)declaration).ReturnType); case SyntaxKind.FieldDeclaration: return ((FieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).Type; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).Type; case SyntaxKind.EventFieldDeclaration: return ((EventFieldDeclarationSyntax)declaration).Declaration.Type; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).Type; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Type; case SyntaxKind.LocalDeclarationStatement: return ((LocalDeclarationStatementSyntax)declaration).Declaration.Type; case SyntaxKind.VariableDeclaration: return ((VariableDeclarationSyntax)declaration).Type; case SyntaxKind.VariableDeclarator: if (declaration.Parent != null) { return this.GetType(declaration.Parent); } break; } return null; } private static TypeSyntax NotVoid(TypeSyntax type) => type is PredefinedTypeSyntax pd && pd.Keyword.IsKind(SyntaxKind.VoidKeyword) ? null : type; public override SyntaxNode WithType(SyntaxNode declaration, SyntaxNode type) => this.Isolate(declaration, d => WithTypeInternal(d, type)); private static SyntaxNode WithTypeInternal(SyntaxNode declaration, SyntaxNode type) => declaration.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).WithReturnType((TypeSyntax)type), SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(((FieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(((EventFieldDeclarationSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.EventDeclaration => ((EventDeclarationSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.Parameter => ((ParameterSyntax)declaration).WithType((TypeSyntax)type), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(((LocalDeclarationStatementSyntax)declaration).Declaration.WithType((TypeSyntax)type)), SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).WithType((TypeSyntax)type), _ => declaration, }; private SyntaxNode Isolate(SyntaxNode declaration, Func<SyntaxNode, SyntaxNode> editor) { var isolated = this.AsIsolatedDeclaration(declaration); return PreserveTrivia(isolated, editor); } private SyntaxNode AsIsolatedDeclaration(SyntaxNode declaration) { if (declaration != null) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Parent != null && vd.Variables.Count == 1) { return this.AsIsolatedDeclaration(vd.Parent); } break; case SyntaxKind.VariableDeclarator: var v = (VariableDeclaratorSyntax)declaration; if (v.Parent != null && v.Parent.Parent != null) { return this.ClearTrivia(WithVariable(v.Parent.Parent, v)); } break; case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent != null) { var attrList = (AttributeListSyntax)attr.Parent; return attrList.WithAttributes(SyntaxFactory.SingletonSeparatedList(attr)).WithTarget(null); } break; } } return declaration; } private static SyntaxNode WithVariable(SyntaxNode declaration, VariableDeclaratorSyntax variable) { var vd = GetVariableDeclaration(declaration); if (vd != null) { return WithVariableDeclaration(declaration, vd.WithVariables(SyntaxFactory.SingletonSeparatedList(variable))); } return declaration; } private static VariableDeclarationSyntax GetVariableDeclaration(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration, _ => null, }; private static SyntaxNode WithVariableDeclaration(SyntaxNode declaration, VariableDeclarationSyntax variables) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).WithDeclaration(variables), SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).WithDeclaration(variables), _ => declaration, }; private static SyntaxNode GetFullDeclaration(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (CSharpSyntaxFacts.ParentIsFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsEventFieldDeclaration(vd) || CSharpSyntaxFacts.ParentIsLocalDeclarationStatement(vd)) { return vd.Parent; } else { return vd; } case SyntaxKind.VariableDeclarator: case SyntaxKind.Attribute: if (declaration.Parent != null) { return GetFullDeclaration(declaration.Parent); } break; } return declaration; } private SyntaxNode AsNodeLike(SyntaxNode existingNode, SyntaxNode newNode) { switch (this.GetDeclarationKind(existingNode)) { case DeclarationKind.Class: case DeclarationKind.Interface: case DeclarationKind.Struct: case DeclarationKind.Enum: case DeclarationKind.Namespace: case DeclarationKind.CompilationUnit: var container = this.GetDeclaration(existingNode.Parent); if (container != null) { return this.AsMemberOf(container, newNode); } break; case DeclarationKind.Attribute: return AsAttributeList(newNode); } return newNode; } public override IReadOnlyList<SyntaxNode> GetParameters(SyntaxNode declaration) { var list = declaration.GetParameterList(); return list != null ? list.Parameters : declaration is SimpleLambdaExpressionSyntax simpleLambda ? new[] { simpleLambda.Parameter } : SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertParameters(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> parameters) { var newParameters = AsParameterList(parameters); var currentList = declaration.GetParameterList(); if (currentList == null) { currentList = declaration.IsKind(SyntaxKind.IndexerDeclaration) ? SyntaxFactory.BracketedParameterList() : (BaseParameterListSyntax)SyntaxFactory.ParameterList(); } var newList = currentList.WithParameters(currentList.Parameters.InsertRange(index, newParameters.Parameters)); return WithParameterList(declaration, newList); } public override IReadOnlyList<SyntaxNode> GetSwitchSections(SyntaxNode switchStatement) { var statement = switchStatement as SwitchStatementSyntax; return statement?.Sections ?? SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } public override SyntaxNode InsertSwitchSections(SyntaxNode switchStatement, int index, IEnumerable<SyntaxNode> switchSections) { if (!(switchStatement is SwitchStatementSyntax statement)) { return switchStatement; } var newSections = statement.Sections.InsertRange(index, switchSections.Cast<SwitchSectionSyntax>()); return AddMissingTokens(statement, recurse: false).WithSections(newSections); } private static TNode AddMissingTokens<TNode>(TNode node, bool recurse) where TNode : CSharpSyntaxNode { var rewriter = new AddMissingTokensRewriter(recurse); return (TNode)rewriter.Visit(node); } private class AddMissingTokensRewriter : CSharpSyntaxRewriter { private readonly bool _recurse; private bool _firstVisit = true; public AddMissingTokensRewriter(bool recurse) => _recurse = recurse; public override SyntaxNode Visit(SyntaxNode node) { if (!_recurse && !_firstVisit) { return node; } _firstVisit = false; return base.Visit(node); } public override SyntaxToken VisitToken(SyntaxToken token) { var rewrittenToken = base.VisitToken(token); if (!rewrittenToken.IsMissing || !CSharp.SyntaxFacts.IsPunctuationOrKeyword(token.Kind())) { return rewrittenToken; } return SyntaxFactory.Token(token.Kind()).WithTriviaFrom(rewrittenToken); } } internal override SyntaxNode GetParameterListNode(SyntaxNode declaration) => declaration.GetParameterList(); private static SyntaxNode WithParameterList(SyntaxNode declaration, BaseParameterListSyntax list) { switch (declaration.Kind()) { case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).WithParameterList(list); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithParameterList((ParameterListSyntax)list); case SyntaxKind.SimpleLambdaExpression: var lambda = (SimpleLambdaExpressionSyntax)declaration; var parameters = list.Parameters; if (parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return lambda.WithParameter(parameters[0]); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), lambda.Body) .WithLeadingTrivia(lambda.GetLeadingTrivia()) .WithTrailingTrivia(lambda.GetTrailingTrivia()); } case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((RecordDeclarationSyntax)declaration).WithParameterList((ParameterListSyntax)list); default: return declaration; } } public override SyntaxNode GetExpression(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).Body as ExpressionSyntax; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return pd.ExpressionBody.Expression; } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return id.ExpressionBody.Expression; } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return method.ExpressionBody.Expression; } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return local.ExpressionBody.Expression; } goto default; default: return GetEqualsValue(declaration)?.Value; } } public override SyntaxNode WithExpression(SyntaxNode declaration, SyntaxNode expression) => this.Isolate(declaration, d => WithExpressionInternal(d, expression)); private static SyntaxNode WithExpressionInternal(SyntaxNode declaration, SyntaxNode expression) { var expr = (ExpressionSyntax)expression; switch (declaration.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody((CSharpSyntaxNode)expr ?? CreateBlock(null)); case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; if (pd.ExpressionBody != null) { return ReplaceWithTrivia(pd, pd.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.IndexerDeclaration: var id = (IndexerDeclarationSyntax)declaration; if (id.ExpressionBody != null) { return ReplaceWithTrivia(id, id.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExpressionBody != null) { return ReplaceWithTrivia(method, method.ExpressionBody.Expression, expr); } goto default; case SyntaxKind.LocalFunctionStatement: var local = (LocalFunctionStatementSyntax)declaration; if (local.ExpressionBody != null) { return ReplaceWithTrivia(local, local.ExpressionBody.Expression, expr); } goto default; default: var eq = GetEqualsValue(declaration); if (eq != null) { if (expression == null) { return WithEqualsValue(declaration, null); } else { // use replace so we only change the value part. return ReplaceWithTrivia(declaration, eq.Value, expr); } } else if (expression != null) { return WithEqualsValue(declaration, SyntaxFactory.EqualsValueClause(expr)); } else { return declaration; } } } private static EqualsValueClauseSyntax GetEqualsValue(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return fd.Declaration.Variables[0].Initializer; } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.Initializer; case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ld.Declaration.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return vd.Variables[0].Initializer; } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).Initializer; case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).Default; } return null; } private static SyntaxNode WithEqualsValue(SyntaxNode declaration, EqualsValueClauseSyntax eq) { switch (declaration.Kind()) { case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, fd.Declaration.Variables[0], fd.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.PropertyDeclaration: var pd = (PropertyDeclarationSyntax)declaration; return pd.WithInitializer(eq); case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration.Variables.Count == 1) { return ReplaceWithTrivia(declaration, ld.Declaration.Variables[0], ld.Declaration.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclaration: var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1) { return ReplaceWithTrivia(declaration, vd.Variables[0], vd.Variables[0].WithInitializer(eq)); } break; case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)declaration).WithInitializer(eq); case SyntaxKind.Parameter: return ((ParameterSyntax)declaration).WithDefault(eq); } return declaration; } private static readonly IReadOnlyList<SyntaxNode> s_EmptyList = SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); public override IReadOnlyList<SyntaxNode> GetStatements(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).Body?.Statements ?? s_EmptyList; case SyntaxKind.AnonymousMethodExpression: return (((AnonymousMethodExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.ParenthesizedLambdaExpression: return (((ParenthesizedLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.SimpleLambdaExpression: return (((SimpleLambdaExpressionSyntax)declaration).Body as BlockSyntax)?.Statements ?? s_EmptyList; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).Body?.Statements ?? s_EmptyList; default: return s_EmptyList; } } public override SyntaxNode WithStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) { var body = CreateBlock(statements); var somebody = statements != null ? body : null; var semicolon = statements == null ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default; switch (declaration.Kind()) { case SyntaxKind.MethodDeclaration: return ((MethodDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.OperatorDeclaration: return ((OperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConversionOperatorDeclaration: return ((ConversionOperatorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.ConstructorDeclaration: return ((ConstructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.DestructorDeclaration: return ((DestructorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.LocalFunctionStatement: return ((LocalFunctionStatementSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)declaration).WithBody(body); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)declaration).WithBody(body); case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return ((AccessorDeclarationSyntax)declaration).WithBody(somebody).WithSemicolonToken(semicolon).WithExpressionBody(null); default: return declaration; } } public override IReadOnlyList<SyntaxNode> GetAccessors(SyntaxNode declaration) { var list = GetAccessorList(declaration); return list?.Accessors ?? s_EmptyList; } public override SyntaxNode InsertAccessors(SyntaxNode declaration, int index, IEnumerable<SyntaxNode> accessors) { var newAccessors = AsAccessorList(accessors, declaration.Kind()); var currentList = GetAccessorList(declaration); if (currentList == null) { if (CanHaveAccessors(declaration)) { currentList = SyntaxFactory.AccessorList(); } else { return declaration; } } var newList = currentList.WithAccessors(currentList.Accessors.InsertRange(index, newAccessors.Accessors)); return WithAccessorList(declaration, newList); } internal static AccessorListSyntax GetAccessorList(SyntaxNode declaration) => (declaration as BasePropertyDeclarationSyntax)?.AccessorList; private static bool CanHaveAccessors(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.PropertyDeclaration => ((PropertyDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ExpressionBody == null, SyntaxKind.EventDeclaration => true, _ => false, }; private static SyntaxNode WithAccessorList(SyntaxNode declaration, AccessorListSyntax accessorList) => declaration switch { BasePropertyDeclarationSyntax baseProperty => baseProperty.WithAccessorList(accessorList), _ => declaration, }; private static AccessorListSyntax AsAccessorList(IEnumerable<SyntaxNode> nodes, SyntaxKind parentKind) { return SyntaxFactory.AccessorList( SyntaxFactory.List(nodes.Select(n => AsAccessor(n, parentKind)).Where(n => n != null))); } private static AccessorDeclarationSyntax AsAccessor(SyntaxNode node, SyntaxKind parentKind) { switch (parentKind) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: switch (node.Kind()) { case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; case SyntaxKind.EventDeclaration: switch (node.Kind()) { case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return (AccessorDeclarationSyntax)node; } break; } return null; } private static AccessorDeclarationSyntax GetAccessor(SyntaxNode declaration, SyntaxKind kind) { var accessorList = GetAccessorList(declaration); return accessorList?.Accessors.FirstOrDefault(a => a.IsKind(kind)); } private SyntaxNode WithAccessor(SyntaxNode declaration, SyntaxKind kind, AccessorDeclarationSyntax accessor) => this.WithAccessor(declaration, GetAccessorList(declaration), kind, accessor); private SyntaxNode WithAccessor(SyntaxNode declaration, AccessorListSyntax accessorList, SyntaxKind kind, AccessorDeclarationSyntax accessor) { if (accessorList != null) { var acc = accessorList.Accessors.FirstOrDefault(a => a.IsKind(kind)); if (acc != null) { return this.ReplaceNode(declaration, acc, accessor); } else if (accessor != null) { return this.ReplaceNode(declaration, accessorList, accessorList.AddAccessors(accessor)); } } return declaration; } public override IReadOnlyList<SyntaxNode> GetGetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.GetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override IReadOnlyList<SyntaxNode> GetSetAccessorStatements(SyntaxNode declaration) { var accessor = GetAccessor(declaration, SyntaxKind.SetAccessorDeclaration); return accessor?.Body?.Statements ?? s_EmptyList; } public override SyntaxNode WithGetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.GetAccessorDeclaration, statements); public override SyntaxNode WithSetAccessorStatements(SyntaxNode declaration, IEnumerable<SyntaxNode> statements) => this.WithAccessorStatements(declaration, SyntaxKind.SetAccessorDeclaration, statements); private SyntaxNode WithAccessorStatements(SyntaxNode declaration, SyntaxKind kind, IEnumerable<SyntaxNode> statements) { var accessor = GetAccessor(declaration, kind); if (accessor == null) { accessor = AccessorDeclaration(kind, statements); return this.WithAccessor(declaration, kind, accessor); } else { return this.WithAccessor(declaration, kind, (AccessorDeclarationSyntax)this.WithStatements(accessor, statements)); } } public override IReadOnlyList<SyntaxNode> GetBaseAndInterfaceTypes(SyntaxNode declaration) { var baseList = GetBaseList(declaration); if (baseList != null) { return baseList.Types.OfType<SimpleBaseTypeSyntax>().Select(bt => bt.Type).ToReadOnlyCollection(); } else { return SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(); } } public override SyntaxNode AddBaseType(SyntaxNode declaration, SyntaxNode baseType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(0, SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)baseType)))); } } public override SyntaxNode AddInterfaceType(SyntaxNode declaration, SyntaxNode interfaceType) { var baseList = GetBaseList(declaration); if (baseList != null) { return WithBaseList(declaration, baseList.WithTypes(baseList.Types.Insert(baseList.Types.Count, SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } else { return AddBaseList(declaration, SyntaxFactory.BaseList(SyntaxFactory.SingletonSeparatedList<BaseTypeSyntax>(SyntaxFactory.SimpleBaseType((TypeSyntax)interfaceType)))); } } private static SyntaxNode AddBaseList(SyntaxNode declaration, BaseListSyntax baseList) { var newDecl = WithBaseList(declaration, baseList); // move trivia from type identifier to after base list return ShiftTrivia(newDecl, GetBaseList(newDecl)); } private static BaseListSyntax GetBaseList(SyntaxNode declaration) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.BaseList : null; private static SyntaxNode WithBaseList(SyntaxNode declaration, BaseListSyntax baseList) => declaration is TypeDeclarationSyntax typeDeclaration ? typeDeclaration.WithBaseList(baseList) : declaration; #endregion #region Remove, Replace, Insert public override SyntaxNode ReplaceNode(SyntaxNode root, SyntaxNode declaration, SyntaxNode newDeclaration) { newDeclaration = this.AsNodeLike(declaration, newDeclaration); if (newDeclaration == null) { return this.RemoveNode(root, declaration); } if (root.Span.Contains(declaration.Span)) { var newFullDecl = this.AsIsolatedDeclaration(newDeclaration); var fullDecl = GetFullDeclaration(declaration); // special handling for replacing at location of sub-declaration if (fullDecl != declaration && fullDecl.IsKind(newFullDecl.Kind())) { // try to replace inline if possible if (GetDeclarationCount(newFullDecl) == 1) { var newSubDecl = GetSubDeclarations(newFullDecl)[0]; if (AreInlineReplaceableSubDeclarations(declaration, newSubDecl)) { return base.ReplaceNode(root, declaration, newSubDecl); } } // replace sub declaration by splitting full declaration and inserting between var index = this.IndexOf(GetSubDeclarations(fullDecl), declaration); // replace declaration with multiple declarations return ReplaceRange(root, fullDecl, this.SplitAndReplace(fullDecl, index, new[] { newDeclaration })); } // attempt normal replace return base.ReplaceNode(root, declaration, newFullDecl); } else { return base.ReplaceNode(root, declaration, newDeclaration); } } // returns true if one sub-declaration can be replaced inline with another sub-declaration private static bool AreInlineReplaceableSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.Attribute: case SyntaxKind.VariableDeclarator: return AreSimilarExceptForSubDeclarations(decl1.Parent, decl2.Parent); } } return false; } private static bool AreSimilarExceptForSubDeclarations(SyntaxNode decl1, SyntaxNode decl2) { if (decl1 == decl2) { return true; } if (decl1 == null || decl2 == null) { return false; } var kind = decl1.Kind(); if (decl2.IsKind(kind)) { switch (kind) { case SyntaxKind.FieldDeclaration: var fd1 = (FieldDeclarationSyntax)decl1; var fd2 = (FieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(fd1.Modifiers, fd2.Modifiers) && SyntaxFactory.AreEquivalent(fd1.AttributeLists, fd2.AttributeLists); case SyntaxKind.EventFieldDeclaration: var efd1 = (EventFieldDeclarationSyntax)decl1; var efd2 = (EventFieldDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(efd1.Modifiers, efd2.Modifiers) && SyntaxFactory.AreEquivalent(efd1.AttributeLists, efd2.AttributeLists); case SyntaxKind.LocalDeclarationStatement: var ld1 = (LocalDeclarationStatementSyntax)decl1; var ld2 = (LocalDeclarationStatementSyntax)decl2; return SyntaxFactory.AreEquivalent(ld1.Modifiers, ld2.Modifiers); case SyntaxKind.AttributeList: // don't compare targets, since aren't part of the abstraction return true; case SyntaxKind.VariableDeclaration: var vd1 = (VariableDeclarationSyntax)decl1; var vd2 = (VariableDeclarationSyntax)decl2; return SyntaxFactory.AreEquivalent(vd1.Type, vd2.Type) && AreSimilarExceptForSubDeclarations(vd1.Parent, vd2.Parent); } } return false; } // replaces sub-declaration by splitting multi-part declaration first private IEnumerable<SyntaxNode> SplitAndReplace(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); if (index >= 0 && index < count) { var newNodes = new List<SyntaxNode>(); if (index > 0) { // make a single declaration with only sub-declarations before the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); } newNodes.AddRange(newDeclarations); if (index < count - 1) { // make a single declaration with only the sub-declarations after the sub-declaration being replaced newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index + 1).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); } return newNodes; } else { return newDeclarations; } } public override SyntaxNode InsertNodesBefore(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesBeforeInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesBefore(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesBeforeInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesBefore(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index > 0) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index, newDeclarations)); } return base.InsertNodesBefore(root, fullDecl, newDeclarations); } public override SyntaxNode InsertNodesAfter(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { if (declaration.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Insert global statements before this global statement declaration = declaration.Parent; newDeclarations = newDeclarations.Select(declaration => declaration is StatementSyntax statement ? SyntaxFactory.GlobalStatement(statement) : declaration); } if (root.Span.Contains(declaration.Span)) { return this.Isolate(root.TrackNodes(declaration), r => this.InsertNodesAfterInternal(r, r.GetCurrentNode(declaration), newDeclarations)); } else { return base.InsertNodesAfter(root, declaration, newDeclarations); } } private SyntaxNode InsertNodesAfterInternal(SyntaxNode root, SyntaxNode declaration, IEnumerable<SyntaxNode> newDeclarations) { var fullDecl = GetFullDeclaration(declaration); if (fullDecl == declaration || GetDeclarationCount(fullDecl) == 1) { return base.InsertNodesAfter(root, fullDecl, newDeclarations); } var subDecls = GetSubDeclarations(fullDecl); var count = subDecls.Count; var index = this.IndexOf(subDecls, declaration); // insert new declaration between full declaration split into two if (index >= 0 && index < count - 1) { return ReplaceRange(root, fullDecl, this.SplitAndInsert(fullDecl, index + 1, newDeclarations)); } return base.InsertNodesAfter(root, fullDecl, newDeclarations); } private IEnumerable<SyntaxNode> SplitAndInsert(SyntaxNode multiPartDeclaration, int index, IEnumerable<SyntaxNode> newDeclarations) { var count = GetDeclarationCount(multiPartDeclaration); var newNodes = new List<SyntaxNode>(); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, index, count - index).WithTrailingTrivia(SyntaxFactory.ElasticSpace)); newNodes.AddRange(newDeclarations); newNodes.Add(this.WithSubDeclarationsRemoved(multiPartDeclaration, 0, index).WithLeadingTrivia(SyntaxFactory.ElasticSpace)); return newNodes; } private SyntaxNode WithSubDeclarationsRemoved(SyntaxNode declaration, int index, int count) => this.RemoveNodes(declaration, GetSubDeclarations(declaration).Skip(index).Take(count)); private static IReadOnlyList<SyntaxNode> GetSubDeclarations(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.FieldDeclaration => ((FieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.EventFieldDeclaration => ((EventFieldDeclarationSyntax)declaration).Declaration.Variables, SyntaxKind.LocalDeclarationStatement => ((LocalDeclarationStatementSyntax)declaration).Declaration.Variables, SyntaxKind.VariableDeclaration => ((VariableDeclarationSyntax)declaration).Variables, SyntaxKind.AttributeList => ((AttributeListSyntax)declaration).Attributes, _ => SpecializedCollections.EmptyReadOnlyList<SyntaxNode>(), }; public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node) => this.RemoveNode(root, node, DefaultRemoveOptions); public override SyntaxNode RemoveNode(SyntaxNode root, SyntaxNode node, SyntaxRemoveOptions options) { if (node.Parent.IsKind(SyntaxKind.GlobalStatement)) { // Remove the entire global statement as part of the edit node = node.Parent; } if (root.Span.Contains(node.Span)) { // node exists within normal span of the root (not in trivia) return this.Isolate(root.TrackNodes(node), r => this.RemoveNodeInternal(r, r.GetCurrentNode(node), options)); } else { return this.RemoveNodeInternal(root, node, options); } } private SyntaxNode RemoveNodeInternal(SyntaxNode root, SyntaxNode declaration, SyntaxRemoveOptions options) { switch (declaration.Kind()) { case SyntaxKind.Attribute: var attr = (AttributeSyntax)declaration; if (attr.Parent is AttributeListSyntax attrList && attrList.Attributes.Count == 1) { // remove entire list if only one attribute return this.RemoveNodeInternal(root, attrList, options); } break; case SyntaxKind.AttributeArgument: if (declaration.Parent != null && ((AttributeArgumentListSyntax)declaration.Parent).Arguments.Count == 1) { // remove entire argument list if only one argument return this.RemoveNodeInternal(root, declaration.Parent, options); } break; case SyntaxKind.VariableDeclarator: var full = GetFullDeclaration(declaration); if (full != declaration && GetDeclarationCount(full) == 1) { // remove full declaration if only one declarator return this.RemoveNodeInternal(root, full, options); } break; case SyntaxKind.SimpleBaseType: if (declaration.Parent is BaseListSyntax baseList && baseList.Types.Count == 1) { // remove entire base list if this is the only base type. return this.RemoveNodeInternal(root, baseList, options); } break; default: var parent = declaration.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.SimpleBaseType: return this.RemoveNodeInternal(root, parent, options); } } break; } return base.RemoveNode(root, declaration, options); } /// <summary> /// Moves the trailing trivia from the node's previous token to the end of the node /// </summary> private static SyntaxNode ShiftTrivia(SyntaxNode root, SyntaxNode node) { var firstToken = node.GetFirstToken(); var previousToken = firstToken.GetPreviousToken(); if (previousToken != default && root.Contains(previousToken.Parent)) { var newNode = node.WithTrailingTrivia(node.GetTrailingTrivia().AddRange(previousToken.TrailingTrivia)); var newPreviousToken = previousToken.WithTrailingTrivia(default(SyntaxTriviaList)); return root.ReplaceSyntax( nodes: new[] { node }, computeReplacementNode: (o, r) => newNode, tokens: new[] { previousToken }, computeReplacementToken: (o, r) => newPreviousToken, trivia: null, computeReplacementTrivia: null); } return root; } internal override bool IsRegularOrDocComment(SyntaxTrivia trivia) => trivia.IsRegularOrDocComment(); #endregion #region Statements and Expressions public override SyntaxNode AddEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.AddAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode RemoveEventHandler(SyntaxNode @event, SyntaxNode handler) => SyntaxFactory.AssignmentExpression(SyntaxKind.SubtractAssignmentExpression, (ExpressionSyntax)@event, (ExpressionSyntax)Parenthesize(handler)); public override SyntaxNode AwaitExpression(SyntaxNode expression) => SyntaxFactory.AwaitExpression((ExpressionSyntax)expression); public override SyntaxNode NameOfExpression(SyntaxNode expression) => this.InvocationExpression(s_nameOfIdentifier, expression); public override SyntaxNode ReturnStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ReturnStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowStatement(SyntaxNode expressionOpt = null) => SyntaxFactory.ThrowStatement((ExpressionSyntax)expressionOpt); public override SyntaxNode ThrowExpression(SyntaxNode expression) => SyntaxFactory.ThrowExpression((ExpressionSyntax)expression); internal override bool SupportsThrowExpression() => true; public override SyntaxNode IfStatement(SyntaxNode condition, IEnumerable<SyntaxNode> trueStatements, IEnumerable<SyntaxNode> falseStatements = null) { if (falseStatements == null) { return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements)); } else { var falseArray = falseStatements.ToList(); // make else-if chain if false-statements contain only an if-statement return SyntaxFactory.IfStatement( (ExpressionSyntax)condition, CreateBlock(trueStatements), SyntaxFactory.ElseClause( falseArray.Count == 1 && falseArray[0] is IfStatementSyntax ? (StatementSyntax)falseArray[0] : CreateBlock(falseArray))); } } private static BlockSyntax CreateBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(AsStatementList(statements)).WithAdditionalAnnotations(Simplifier.Annotation); private static SyntaxList<StatementSyntax> AsStatementList(IEnumerable<SyntaxNode> nodes) => nodes == null ? default : SyntaxFactory.List(nodes.Select(AsStatement)); private static StatementSyntax AsStatement(SyntaxNode node) { if (node is ExpressionSyntax expression) { return SyntaxFactory.ExpressionStatement(expression); } return (StatementSyntax)node; } public override SyntaxNode ExpressionStatement(SyntaxNode expression) => SyntaxFactory.ExpressionStatement((ExpressionSyntax)expression); internal override SyntaxNode MemberAccessExpressionWorker(SyntaxNode expression, SyntaxNode simpleName) { return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, ParenthesizeLeft((ExpressionSyntax)expression), (SimpleNameSyntax)simpleName); } public override SyntaxNode ConditionalAccessExpression(SyntaxNode expression, SyntaxNode whenNotNull) => SyntaxGeneratorInternal.ConditionalAccessExpression(expression, whenNotNull); public override SyntaxNode MemberBindingExpression(SyntaxNode name) => SyntaxGeneratorInternal.MemberBindingExpression(name); public override SyntaxNode ElementBindingExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementBindingExpression( SyntaxFactory.BracketedArgumentList(SyntaxFactory.SeparatedList(arguments))); /// <summary> /// Parenthesize the left hand size of a member access, invocation or element access expression /// </summary> private static ExpressionSyntax ParenthesizeLeft(ExpressionSyntax expression) { if (expression is TypeSyntax || expression.IsKind(SyntaxKind.ThisExpression) || expression.IsKind(SyntaxKind.BaseExpression) || expression.IsKind(SyntaxKind.ParenthesizedExpression) || expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || expression.IsKind(SyntaxKind.InvocationExpression) || expression.IsKind(SyntaxKind.ElementAccessExpression) || expression.IsKind(SyntaxKind.MemberBindingExpression)) { return expression; } return (ExpressionSyntax)Parenthesize(expression); } private static SeparatedSyntaxList<ExpressionSyntax> AsExpressionList(IEnumerable<SyntaxNode> expressions) => SyntaxFactory.SeparatedList(expressions.OfType<ExpressionSyntax>()); public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, SyntaxNode size) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)size)))); return SyntaxFactory.ArrayCreationExpression(arrayType); } public override SyntaxNode ArrayCreationExpression(SyntaxNode elementType, IEnumerable<SyntaxNode> elements) { var arrayType = SyntaxFactory.ArrayType((TypeSyntax)elementType, SyntaxFactory.SingletonList( SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.SingletonSeparatedList((ExpressionSyntax)SyntaxFactory.OmittedArraySizeExpression())))); var initializer = SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression, AsExpressionList(elements)); return SyntaxFactory.ArrayCreationExpression(arrayType, initializer); } public override SyntaxNode ObjectCreationExpression(SyntaxNode type, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ObjectCreationExpression((TypeSyntax)type, CreateArgumentList(arguments), null); internal override SyntaxNode ObjectCreationExpression(SyntaxNode type, SyntaxToken openParen, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParen) => SyntaxFactory.ObjectCreationExpression( (TypeSyntax)type, SyntaxFactory.ArgumentList(openParen, arguments, closeParen), initializer: null); private static ArgumentListSyntax CreateArgumentList(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ArgumentList(CreateArguments(arguments)); private static SeparatedSyntaxList<ArgumentSyntax> CreateArguments(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.SeparatedList(arguments.Select(AsArgument)); private static ArgumentSyntax AsArgument(SyntaxNode argOrExpression) => argOrExpression as ArgumentSyntax ?? SyntaxFactory.Argument((ExpressionSyntax)argOrExpression); public override SyntaxNode InvocationExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.InvocationExpression(ParenthesizeLeft((ExpressionSyntax)expression), CreateArgumentList(arguments)); public override SyntaxNode ElementAccessExpression(SyntaxNode expression, IEnumerable<SyntaxNode> arguments) => SyntaxFactory.ElementAccessExpression(ParenthesizeLeft((ExpressionSyntax)expression), SyntaxFactory.BracketedArgumentList(CreateArguments(arguments))); internal override SyntaxToken NumericLiteralToken(string text, ulong value) => SyntaxFactory.Literal(text, value); public override SyntaxNode DefaultExpression(SyntaxNode type) => SyntaxFactory.DefaultExpression((TypeSyntax)type).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode DefaultExpression(ITypeSymbol type) { // If it's just a reference type, then "null" is the default expression for it. Note: // this counts for actual reference type, or a type parameter with a 'class' constraint. // Also, if it's a nullable type, then we can use "null". if (type.IsReferenceType || type.IsPointerType() || type.IsNullable()) { return SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression); } switch (type.SpecialType) { case SpecialType.System_Boolean: return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression); case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Decimal: case SpecialType.System_Single: case SpecialType.System_Double: return SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal("0", 0)); } // Default to a "default(<typename>)" expression. return DefaultExpression(type.GenerateTypeSyntax()); } private static SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia = true, bool addSimplifierAnnotation = true) => CSharpSyntaxGeneratorInternal.Parenthesize(expression, includeElasticTrivia, addSimplifierAnnotation); public override SyntaxNode IsTypeExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.IsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode TypeOfExpression(SyntaxNode type) => SyntaxFactory.TypeOfExpression((TypeSyntax)type); public override SyntaxNode TryCastExpression(SyntaxNode expression, SyntaxNode type) => SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, (ExpressionSyntax)Parenthesize(expression), (TypeSyntax)type); public override SyntaxNode CastExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode ConvertExpression(SyntaxNode type, SyntaxNode expression) => SyntaxFactory.CastExpression((TypeSyntax)type, (ExpressionSyntax)Parenthesize(expression)).WithAdditionalAnnotations(Simplifier.Annotation); public override SyntaxNode AssignmentStatement(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, (ExpressionSyntax)left, (ExpressionSyntax)Parenthesize(right)); private static SyntaxNode CreateBinaryExpression(SyntaxKind syntaxKind, SyntaxNode left, SyntaxNode right) => SyntaxFactory.BinaryExpression(syntaxKind, (ExpressionSyntax)Parenthesize(left), (ExpressionSyntax)Parenthesize(right)); public override SyntaxNode ValueEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ReferenceEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.EqualsExpression, left, right); public override SyntaxNode ValueNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode ReferenceNotEqualsExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.NotEqualsExpression, left, right); public override SyntaxNode LessThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanExpression, left, right); public override SyntaxNode LessThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LessThanOrEqualExpression, left, right); public override SyntaxNode GreaterThanExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanExpression, left, right); public override SyntaxNode GreaterThanOrEqualExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.GreaterThanOrEqualExpression, left, right); public override SyntaxNode NegateExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.UnaryMinusExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode AddExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.AddExpression, left, right); public override SyntaxNode SubtractExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.SubtractExpression, left, right); public override SyntaxNode MultiplyExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.MultiplyExpression, left, right); public override SyntaxNode DivideExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.DivideExpression, left, right); public override SyntaxNode ModuloExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.ModuloExpression, left, right); public override SyntaxNode BitwiseAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseAndExpression, left, right); public override SyntaxNode BitwiseOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.BitwiseOrExpression, left, right); public override SyntaxNode BitwiseNotExpression(SyntaxNode operand) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.BitwiseNotExpression, (ExpressionSyntax)Parenthesize(operand)); public override SyntaxNode LogicalAndExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalAndExpression, left, right); public override SyntaxNode LogicalOrExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.LogicalOrExpression, left, right); public override SyntaxNode LogicalNotExpression(SyntaxNode expression) => SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, (ExpressionSyntax)Parenthesize(expression)); public override SyntaxNode ConditionalExpression(SyntaxNode condition, SyntaxNode whenTrue, SyntaxNode whenFalse) => SyntaxFactory.ConditionalExpression((ExpressionSyntax)Parenthesize(condition), (ExpressionSyntax)Parenthesize(whenTrue), (ExpressionSyntax)Parenthesize(whenFalse)); public override SyntaxNode CoalesceExpression(SyntaxNode left, SyntaxNode right) => CreateBinaryExpression(SyntaxKind.CoalesceExpression, left, right); public override SyntaxNode ThisExpression() => SyntaxFactory.ThisExpression(); public override SyntaxNode BaseExpression() => SyntaxFactory.BaseExpression(); public override SyntaxNode LiteralExpression(object value) => ExpressionGenerator.GenerateNonEnumValueExpression(null, value, canUseFieldReference: true); public override SyntaxNode TypedConstantExpression(TypedConstant value) => ExpressionGenerator.GenerateExpression(value); public override SyntaxNode IdentifierName(string identifier) => identifier.ToIdentifierName(); public override SyntaxNode GenericName(string identifier, IEnumerable<SyntaxNode> typeArguments) => GenericName(identifier.ToIdentifierToken(), typeArguments); internal override SyntaxNode GenericName(SyntaxToken identifier, IEnumerable<SyntaxNode> typeArguments) => SyntaxFactory.GenericName(identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); public override SyntaxNode WithTypeArguments(SyntaxNode expression, IEnumerable<SyntaxNode> typeArguments) { switch (expression.Kind()) { case SyntaxKind.IdentifierName: var sname = (SimpleNameSyntax)expression; return SyntaxFactory.GenericName(sname.Identifier, SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.GenericName: var gname = (GenericNameSyntax)expression; return gname.WithTypeArgumentList(SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments.Cast<TypeSyntax>()))); case SyntaxKind.QualifiedName: var qname = (QualifiedNameSyntax)expression; return qname.WithRight((SimpleNameSyntax)this.WithTypeArguments(qname.Right, typeArguments)); case SyntaxKind.AliasQualifiedName: var aname = (AliasQualifiedNameSyntax)expression; return aname.WithName((SimpleNameSyntax)this.WithTypeArguments(aname.Name, typeArguments)); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: var sma = (MemberAccessExpressionSyntax)expression; return sma.WithName((SimpleNameSyntax)this.WithTypeArguments(sma.Name, typeArguments)); default: return expression; } } public override SyntaxNode QualifiedName(SyntaxNode left, SyntaxNode right) => SyntaxFactory.QualifiedName((NameSyntax)left, (SimpleNameSyntax)right).WithAdditionalAnnotations(Simplifier.Annotation); internal override SyntaxNode GlobalAliasedName(SyntaxNode name) => SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)name); public override SyntaxNode NameExpression(INamespaceOrTypeSymbol namespaceOrTypeSymbol) => namespaceOrTypeSymbol.GenerateNameSyntax(); public override SyntaxNode TypeExpression(ITypeSymbol typeSymbol) => typeSymbol.GenerateTypeSyntax(); public override SyntaxNode TypeExpression(SpecialType specialType) => specialType switch { SpecialType.System_Boolean => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)), SpecialType.System_Byte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword)), SpecialType.System_Char => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.CharKeyword)), SpecialType.System_Decimal => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DecimalKeyword)), SpecialType.System_Double => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.DoubleKeyword)), SpecialType.System_Int16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ShortKeyword)), SpecialType.System_Int32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntKeyword)), SpecialType.System_Int64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.LongKeyword)), SpecialType.System_Object => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)), SpecialType.System_SByte => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.SByteKeyword)), SpecialType.System_Single => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.FloatKeyword)), SpecialType.System_String => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.StringKeyword)), SpecialType.System_UInt16 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UShortKeyword)), SpecialType.System_UInt32 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.UIntKeyword)), SpecialType.System_UInt64 => SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ULongKeyword)), _ => throw new NotSupportedException("Unsupported SpecialType"), }; public override SyntaxNode ArrayTypeExpression(SyntaxNode type) => SyntaxFactory.ArrayType((TypeSyntax)type, SyntaxFactory.SingletonList(SyntaxFactory.ArrayRankSpecifier())); public override SyntaxNode NullableTypeExpression(SyntaxNode type) { if (type is NullableTypeSyntax) { return type; } else { return SyntaxFactory.NullableType((TypeSyntax)type); } } internal override SyntaxNode CreateTupleType(IEnumerable<SyntaxNode> elements) => SyntaxFactory.TupleType(SyntaxFactory.SeparatedList(elements.Cast<TupleElementSyntax>())); public override SyntaxNode TupleElementExpression(SyntaxNode type, string name = null) => SyntaxFactory.TupleElement((TypeSyntax)type, name?.ToIdentifierToken() ?? default); public override SyntaxNode Argument(string nameOpt, RefKind refKind, SyntaxNode expression) { return SyntaxFactory.Argument( nameOpt == null ? null : SyntaxFactory.NameColon(nameOpt), GetArgumentModifiers(refKind), (ExpressionSyntax)expression); } public override SyntaxNode LocalDeclarationStatement(SyntaxNode type, string name, SyntaxNode initializer, bool isConst) => CSharpSyntaxGeneratorInternal.Instance.LocalDeclarationStatement(type, name.ToIdentifierToken(), initializer, isConst); public override SyntaxNode UsingStatement(SyntaxNode type, string name, SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( CSharpSyntaxGeneratorInternal.VariableDeclaration(type, name.ToIdentifierToken(), expression), expression: null, statement: CreateBlock(statements)); } public override SyntaxNode UsingStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.UsingStatement( declaration: null, expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode LockStatement(SyntaxNode expression, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.LockStatement( expression: (ExpressionSyntax)expression, statement: CreateBlock(statements)); } public override SyntaxNode TryCatchStatement(IEnumerable<SyntaxNode> tryStatements, IEnumerable<SyntaxNode> catchClauses, IEnumerable<SyntaxNode> finallyStatements = null) { return SyntaxFactory.TryStatement( CreateBlock(tryStatements), catchClauses != null ? SyntaxFactory.List(catchClauses.Cast<CatchClauseSyntax>()) : default, finallyStatements != null ? SyntaxFactory.FinallyClause(CreateBlock(finallyStatements)) : null); } public override SyntaxNode CatchClause(SyntaxNode type, string name, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.CatchClause( SyntaxFactory.CatchDeclaration((TypeSyntax)type, name.ToIdentifierToken()), filter: null, block: CreateBlock(statements)); } public override SyntaxNode WhileStatement(SyntaxNode condition, IEnumerable<SyntaxNode> statements) => SyntaxFactory.WhileStatement((ExpressionSyntax)condition, CreateBlock(statements)); public override SyntaxNode SwitchStatement(SyntaxNode expression, IEnumerable<SyntaxNode> caseClauses) { if (expression is TupleExpressionSyntax) { return SyntaxFactory.SwitchStatement( (ExpressionSyntax)expression, caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList()); } else { return SyntaxFactory.SwitchStatement( SyntaxFactory.Token(SyntaxKind.SwitchKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), (ExpressionSyntax)expression, SyntaxFactory.Token(SyntaxKind.CloseParenToken), SyntaxFactory.Token(SyntaxKind.OpenBraceToken), caseClauses.Cast<SwitchSectionSyntax>().ToSyntaxList(), SyntaxFactory.Token(SyntaxKind.CloseBraceToken)); } } public override SyntaxNode SwitchSection(IEnumerable<SyntaxNode> expressions, IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(AsSwitchLabels(expressions), AsStatementList(statements)); internal override SyntaxNode SwitchSectionFromLabels(IEnumerable<SyntaxNode> labels, IEnumerable<SyntaxNode> statements) { return SyntaxFactory.SwitchSection( labels.Cast<SwitchLabelSyntax>().ToSyntaxList(), AsStatementList(statements)); } public override SyntaxNode DefaultSwitchSection(IEnumerable<SyntaxNode> statements) => SyntaxFactory.SwitchSection(SyntaxFactory.SingletonList(SyntaxFactory.DefaultSwitchLabel() as SwitchLabelSyntax), AsStatementList(statements)); private static SyntaxList<SwitchLabelSyntax> AsSwitchLabels(IEnumerable<SyntaxNode> expressions) { var labels = default(SyntaxList<SwitchLabelSyntax>); if (expressions != null) { labels = labels.AddRange(expressions.Select(e => SyntaxFactory.CaseSwitchLabel((ExpressionSyntax)e))); } return labels; } public override SyntaxNode ExitSwitchStatement() => SyntaxFactory.BreakStatement(); internal override SyntaxNode ScopeBlock(IEnumerable<SyntaxNode> statements) => SyntaxFactory.Block(statements.Cast<StatementSyntax>()); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, SyntaxNode expression) { var parameters = parameterDeclarations?.Cast<ParameterSyntax>().ToList(); if (parameters != null && parameters.Count == 1 && IsSimpleLambdaParameter(parameters[0])) { return SyntaxFactory.SimpleLambdaExpression(parameters[0], (CSharpSyntaxNode)expression); } else { return SyntaxFactory.ParenthesizedLambdaExpression(AsParameterList(parameters), (CSharpSyntaxNode)expression); } } private static bool IsSimpleLambdaParameter(SyntaxNode node) => node is ParameterSyntax p && p.Type == null && p.Default == null && p.Modifiers.Count == 0; public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, SyntaxNode expression) => this.ValueReturningLambdaExpression(lambdaParameters, expression); public override SyntaxNode ValueReturningLambdaExpression(IEnumerable<SyntaxNode> parameterDeclarations, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(parameterDeclarations, CreateBlock(statements)); public override SyntaxNode VoidReturningLambdaExpression(IEnumerable<SyntaxNode> lambdaParameters, IEnumerable<SyntaxNode> statements) => this.ValueReturningLambdaExpression(lambdaParameters, statements); public override SyntaxNode LambdaParameter(string identifier, SyntaxNode type = null) => this.ParameterDeclaration(identifier, type, null, RefKind.None); internal override SyntaxNode IdentifierName(SyntaxToken identifier) => SyntaxFactory.IdentifierName(identifier); internal override SyntaxNode NamedAnonymousObjectMemberDeclarator(SyntaxNode identifier, SyntaxNode expression) { return SyntaxFactory.AnonymousObjectMemberDeclarator( SyntaxFactory.NameEquals((IdentifierNameSyntax)identifier), (ExpressionSyntax)expression); } public override SyntaxNode TupleExpression(IEnumerable<SyntaxNode> arguments) => SyntaxFactory.TupleExpression(SyntaxFactory.SeparatedList(arguments.Select(AsArgument))); internal override SyntaxNode RemoveAllComments(SyntaxNode node) { var modifiedNode = RemoveLeadingAndTrailingComments(node); if (modifiedNode is TypeDeclarationSyntax declarationSyntax) { return declarationSyntax.WithOpenBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.OpenBraceToken)) .WithCloseBraceToken(RemoveLeadingAndTrailingComments(declarationSyntax.CloseBraceToken)); } return modifiedNode; } internal override SyntaxTriviaList RemoveCommentLines(SyntaxTriviaList syntaxTriviaList) { static IEnumerable<IEnumerable<SyntaxTrivia>> splitIntoLines(SyntaxTriviaList triviaList) { var index = 0; for (var i = 0; i < triviaList.Count; i++) { if (triviaList[i].IsEndOfLine()) { yield return triviaList.TakeRange(index, i); index = i + 1; } } if (index < triviaList.Count) { yield return triviaList.TakeRange(index, triviaList.Count - 1); } } var syntaxWithoutComments = splitIntoLines(syntaxTriviaList) .Where(trivia => !trivia.Any(t => t.IsRegularOrDocComment())) .SelectMany(t => t); return new SyntaxTriviaList(syntaxWithoutComments); } internal override SyntaxNode ParseExpression(string stringToParse) => SyntaxFactory.ParseExpression(stringToParse); #endregion } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (!(declaration is NamespaceDeclarationSyntax)) { throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); } var members = Insert(destination.Members, (NamespaceDeclarationSyntax)declaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration.Kind() switch { SyntaxKind.CompilationUnit => ((CompilationUnitSyntax)declaration).WithMembers(default), SyntaxKind.NamespaceDeclaration => ((NamespaceDeclarationSyntax)declaration).WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default), BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { node = (NamespaceDeclarationSyntax)base.VisitNamespaceDeclaration(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) { this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { return string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); } private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode { return TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!; UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node)); public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node)); private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node) { Contract.ThrowIfNull(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode => string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode => TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<NamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) { return GetSymbolsOffOfExpression(name); } if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is INamespaceOrTypeSymbol symbol) { if (_context.IsNameOfContext) { return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); } var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<NamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } return default; } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetSyntaxRootAsync(); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationServiceRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Recommendations { internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected readonly TSyntaxContext _context; protected readonly bool _filterOutOfScopeLocals; protected readonly CancellationToken _cancellationToken; private readonly StringComparer _stringComparerForLanguage; public AbstractRecommendationServiceRunner( TSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) { _context = context; _stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer; _filterOutOfScopeLocals = filterOutOfScopeLocals; _cancellationToken = cancellationToken; } public abstract RecommendedSymbols GetRecommendedSymbols(); public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType); // This code is to help give intellisense in the following case: // query.Include(a => a.SomeProperty).ThenInclude(a => a. // where there are more than one overloads of ThenInclude accepting different types of parameters. private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable) { var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position); return symbols.IsDefault ? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable) : symbols; } private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position) { // Use normal lookup path for this/base parameters. if (parameter.IsThis) return default; // Starting from a. in the example, looking for a => a. if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod) return default; // Cannot proceed without DeclaringSyntaxReferences. // We expect that there is a single DeclaringSyntaxReferences in the scenario. // If anything changes on the compiler side, the approach should be revised. if (owningMethod.DeclaringSyntaxReferences.Length != 1) return default; var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>(); // Check that a => a. belongs to an invocation. // Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a. var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken); if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) && syntaxFactsService.IsArgument(lambdaSyntax.Parent) && syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent))) { return default; } var invocationExpression = lambdaSyntax.Parent.Parent.Parent; var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression); var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent); var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent); var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression); var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty; if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType)) { parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType); } else { // Get all members potentially matching the invocation expression. // We filter them out based on ordinality later. var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken); // parameter.Ordinal is the ordinal within (a,b,c) => b. // For candidate symbols of (a,b,c) => b., get types of all possible b. parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal); // The parameterTypeSymbols may include type parameters, and we want their substituted types if available. parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression); } // For each type of b., return all suitable members. Also, ensure we consider the actual type of the // parameter the compiler inferred as it may have made a completely suitable inference for it. return parameterTypeSymbols .Concat(parameter.Type) .SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false)) .ToImmutableArray(); } private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression) { if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter))) { return parameterTypeSymbols; } var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols(); if (invocationSymbols.Length == 0) { return parameterTypeSymbols; } using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes); foreach (var invocationSymbol in invocationSymbols) { var typeParameters = invocationSymbol.GetTypeParameters(); var typeArguments = invocationSymbol.GetTypeArguments(); foreach (var parameterTypeSymbol in parameterTypeSymbols) { if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter)) { // The typeParameter could be from the containing type, so it may not be // present in this method's list of typeParameters. var index = typeParameters.IndexOf(typeParameter); var concreteType = typeArguments.ElementAtOrDefault(index); // If we couldn't find the concrete type, still consider the typeParameter // as is to provide members of any types it is constrained to (including object) concreteTypes.Add(concreteType ?? typeParameter); } else { concreteTypes.Add(parameterTypeSymbol); } } } return concreteTypes.ToImmutable(); } /// <summary> /// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol. /// </summary> /// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/> /// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length) /// </param> /// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param> /// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param> /// <returns></returns> private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda) { var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName); var builder = ArrayBuilder<ITypeSymbol>.GetInstance(); foreach (var candidateSymbol in candidateSymbols) { if (candidateSymbol is IMethodSymbol method) { if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type)) { continue; } // If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate. // Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>. if (expressionSymbol != null && type is INamedTypeSymbol expressionSymbolNamedTypeCandidate && expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol)) { var allTypeArguments = type.GetAllTypeArguments(); if (allTypeArguments.Length != 1) { continue; } type = allTypeArguments[0]; } if (type.IsDelegateType()) { var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { continue; } var parameters = methods[0].GetParameters(); if (parameters.Length <= ordinalInLambda) { continue; } builder.Add(parameters[ordinalInLambda].Type); } } } return builder.ToImmutableAndFree().Distinct(); } private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType) { if (!string.IsNullOrEmpty(argumentName)) { parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type; return parameterType != null; } // We don't know the argument name, so have to find the parameter based on position if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1)) { if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType) { parameterType = arrayType.ElementType; return true; } else { parameterType = null; return false; } } if (ordinalInInvocation < method.Parameters.Length) { parameterType = method.Parameters[ordinalInInvocation].Type; return true; } parameterType = null; return false; } protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>() where TNamespaceDeclarationSyntax : SyntaxNode { var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>(); if (declarationSyntax == null) { return ImmutableArray<ISymbol>.Empty; } var semanticModel = _context.SemanticModel; var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace( semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken)); var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol) .WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax)); return symbols; } protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax) { // // Apart from filtering out non-namespace symbols, this also filters out the symbol // currently being declared. For example... // // namespace X$$ // // ...X won't show in the completion list (unless it is also declared elsewhere). // // In addition, in VB, it will filter out Bar from the sample below... // // Namespace Goo.$$ // Namespace Bar // End Namespace // End Namespace // // ...unless, again, it's also declared elsewhere. // return recommendationSymbol.IsNamespace() && recommendationSymbol.Locations.Any( candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree && declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan))); } protected ImmutableArray<ISymbol> GetMemberSymbols( ISymbol container, int position, bool excludeInstance, bool useBaseReferenceAccessibility, bool unwrapNullable) { // For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter // information that the compiler may fail to give. if (container is IParameterSymbol parameter) return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable); if (container is not INamespaceOrTypeSymbol namespaceOrType) return ImmutableArray<ISymbol>.Empty; if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol) { namespaceOrType = typeSymbol.RemoveNullableIfPresent(); } return useBaseReferenceAccessibility ? _context.SemanticModel.LookupBaseMembers(position) : LookupSymbolsInContainer(namespaceOrType, position, excludeInstance); } protected ImmutableArray<ISymbol> LookupSymbolsInContainer( INamespaceOrTypeSymbol container, int position, bool excludeInstance) { return excludeInstance ? _context.SemanticModel.LookupStaticMembers(position, container) : SuppressDefaultTupleElements( container, _context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true)); } /// <summary> /// If container is a tuple type, any of its tuple element which has a friendly name will cause /// the suppression of the corresponding default name (ItemN). /// In that case, Rest is also removed. /// </summary> protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements( INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols) { var namedType = container as INamedTypeSymbol; if (namedType?.IsTupleType != true) { // container is not a tuple return symbols; } //return tuple elements followed by other members that are not fields return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements). Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Recommendations { internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected readonly TSyntaxContext _context; protected readonly bool _filterOutOfScopeLocals; protected readonly CancellationToken _cancellationToken; private readonly StringComparer _stringComparerForLanguage; public AbstractRecommendationServiceRunner( TSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) { _context = context; _stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer; _filterOutOfScopeLocals = filterOutOfScopeLocals; _cancellationToken = cancellationToken; } public abstract RecommendedSymbols GetRecommendedSymbols(); public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType); // This code is to help give intellisense in the following case: // query.Include(a => a.SomeProperty).ThenInclude(a => a. // where there are more than one overloads of ThenInclude accepting different types of parameters. private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable) { var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position); return symbols.IsDefault ? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable) : symbols; } private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position) { // Use normal lookup path for this/base parameters. if (parameter.IsThis) return default; // Starting from a. in the example, looking for a => a. if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod) return default; // Cannot proceed without DeclaringSyntaxReferences. // We expect that there is a single DeclaringSyntaxReferences in the scenario. // If anything changes on the compiler side, the approach should be revised. if (owningMethod.DeclaringSyntaxReferences.Length != 1) return default; var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>(); // Check that a => a. belongs to an invocation. // Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a. var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken); if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) && syntaxFactsService.IsArgument(lambdaSyntax.Parent) && syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent))) { return default; } var invocationExpression = lambdaSyntax.Parent.Parent.Parent; var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression); var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent); var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent); var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression); var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty; if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType)) { parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType); } else { // Get all members potentially matching the invocation expression. // We filter them out based on ordinality later. var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken); // parameter.Ordinal is the ordinal within (a,b,c) => b. // For candidate symbols of (a,b,c) => b., get types of all possible b. parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal); // The parameterTypeSymbols may include type parameters, and we want their substituted types if available. parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression); } // For each type of b., return all suitable members. Also, ensure we consider the actual type of the // parameter the compiler inferred as it may have made a completely suitable inference for it. return parameterTypeSymbols .Concat(parameter.Type) .SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false)) .ToImmutableArray(); } private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression) { if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter))) { return parameterTypeSymbols; } var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols(); if (invocationSymbols.Length == 0) { return parameterTypeSymbols; } using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes); foreach (var invocationSymbol in invocationSymbols) { var typeParameters = invocationSymbol.GetTypeParameters(); var typeArguments = invocationSymbol.GetTypeArguments(); foreach (var parameterTypeSymbol in parameterTypeSymbols) { if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter)) { // The typeParameter could be from the containing type, so it may not be // present in this method's list of typeParameters. var index = typeParameters.IndexOf(typeParameter); var concreteType = typeArguments.ElementAtOrDefault(index); // If we couldn't find the concrete type, still consider the typeParameter // as is to provide members of any types it is constrained to (including object) concreteTypes.Add(concreteType ?? typeParameter); } else { concreteTypes.Add(parameterTypeSymbol); } } } return concreteTypes.ToImmutable(); } /// <summary> /// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol. /// </summary> /// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/> /// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length) /// </param> /// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param> /// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param> /// <returns></returns> private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda) { var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName); var builder = ArrayBuilder<ITypeSymbol>.GetInstance(); foreach (var candidateSymbol in candidateSymbols) { if (candidateSymbol is IMethodSymbol method) { if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type)) { continue; } // If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate. // Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>. if (expressionSymbol != null && type is INamedTypeSymbol expressionSymbolNamedTypeCandidate && expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol)) { var allTypeArguments = type.GetAllTypeArguments(); if (allTypeArguments.Length != 1) { continue; } type = allTypeArguments[0]; } if (type.IsDelegateType()) { var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { continue; } var parameters = methods[0].GetParameters(); if (parameters.Length <= ordinalInLambda) { continue; } builder.Add(parameters[ordinalInLambda].Type); } } } return builder.ToImmutableAndFree().Distinct(); } private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType) { if (!string.IsNullOrEmpty(argumentName)) { parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type; return parameterType != null; } // We don't know the argument name, so have to find the parameter based on position if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1)) { if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType) { parameterType = arrayType.ElementType; return true; } else { parameterType = null; return false; } } if (ordinalInInvocation < method.Parameters.Length) { parameterType = method.Parameters[ordinalInInvocation].Type; return true; } parameterType = null; return false; } protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>() where TNamespaceDeclarationSyntax : SyntaxNode { var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>(); if (declarationSyntax == null) return ImmutableArray<ISymbol>.Empty; var semanticModel = _context.SemanticModel; var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace( semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken)); var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol) .WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax)); return symbols; } protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax) { // // Apart from filtering out non-namespace symbols, this also filters out the symbol // currently being declared. For example... // // namespace X$$ // // ...X won't show in the completion list (unless it is also declared elsewhere). // // In addition, in VB, it will filter out Bar from the sample below... // // Namespace Goo.$$ // Namespace Bar // End Namespace // End Namespace // // ...unless, again, it's also declared elsewhere. // return recommendationSymbol.IsNamespace() && recommendationSymbol.Locations.Any( candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree && declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan))); } protected ImmutableArray<ISymbol> GetMemberSymbols( ISymbol container, int position, bool excludeInstance, bool useBaseReferenceAccessibility, bool unwrapNullable) { // For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter // information that the compiler may fail to give. if (container is IParameterSymbol parameter) return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable); if (container is not INamespaceOrTypeSymbol namespaceOrType) return ImmutableArray<ISymbol>.Empty; if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol) { namespaceOrType = typeSymbol.RemoveNullableIfPresent(); } return useBaseReferenceAccessibility ? _context.SemanticModel.LookupBaseMembers(position) : LookupSymbolsInContainer(namespaceOrType, position, excludeInstance); } protected ImmutableArray<ISymbol> LookupSymbolsInContainer( INamespaceOrTypeSymbol container, int position, bool excludeInstance) { return excludeInstance ? _context.SemanticModel.LookupStaticMembers(position, container) : SuppressDefaultTupleElements( container, _context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true)); } /// <summary> /// If container is a tuple type, any of its tuple element which has a friendly name will cause /// the suppression of the corresponding default name (ItemN). /// In that case, Rest is also removed. /// </summary> protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements( INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols) { var namedType = container as INamedTypeSymbol; if (namedType?.IsTupleType != true) { // container is not a tuple return symbols; } //return tuple elements followed by other members that are not fields return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements). Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field)); } } }
1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/Option2`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.Immutable; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Marker interface for language specific options. /// </summary> internal interface ILanguageSpecificOption : IOptionWithGroup { } /// <summary> /// Marker interface for language specific options. /// </summary> internal interface ILanguageSpecificOption<T> : ILanguageSpecificOption { } /// <summary> /// An global option. An instance of this class can be used to access an option value from an OptionSet. /// </summary> internal partial class Option2<T> : ILanguageSpecificOption<T> { public OptionDefinition OptionDefinition { get; } /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => OptionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => OptionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => OptionDefinition.Name; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)OptionDefinition.DefaultValue!; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => OptionDefinition.Type; /// <summary> /// Storage locations for the option. /// </summary> public ImmutableArray<OptionStorageLocation2> StorageLocations { get; } public Option2(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: Array.Empty<OptionStorageLocation2>()) { } public Option2(string feature, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal Option2(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { } internal Option2(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false); this.StorageLocations = storageLocations; } #if CODE_STYLE object? IOption2.DefaultValue => this.DefaultValue; bool IOption2.IsPerLanguage => false; #else object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => false; ImmutableArray<OptionStorageLocation> IOption.StorageLocations => this.StorageLocations.As<OptionStorageLocation>(); #endif OptionGroup IOptionWithGroup.Group => this.Group; OptionDefinition IOption2.OptionDefinition => OptionDefinition; public override string ToString() => OptionDefinition.ToString(); public override int GetHashCode() => OptionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); public bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return OptionDefinition == other?.OptionDefinition; } public static implicit operator OptionKey2(Option2<T> option) => new(option); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Marker interface for language specific options. /// </summary> internal interface ILanguageSpecificOption : IOptionWithGroup { } /// <summary> /// Marker interface for language specific options. /// </summary> internal interface ILanguageSpecificOption<T> : ILanguageSpecificOption { } /// <summary> /// An global option. An instance of this class can be used to access an option value from an OptionSet. /// </summary> internal partial class Option2<T> : ILanguageSpecificOption<T> { public OptionDefinition OptionDefinition { get; } /// <inheritdoc cref="OptionDefinition.Feature"/> public string Feature => OptionDefinition.Feature; /// <inheritdoc cref="OptionDefinition.Group"/> internal OptionGroup Group => OptionDefinition.Group; /// <inheritdoc cref="OptionDefinition.Name"/> public string Name => OptionDefinition.Name; /// <inheritdoc cref="OptionDefinition.DefaultValue"/> public T DefaultValue => (T)OptionDefinition.DefaultValue!; /// <inheritdoc cref="OptionDefinition.Type"/> public Type Type => OptionDefinition.Type; /// <summary> /// Storage locations for the option. /// </summary> public ImmutableArray<OptionStorageLocation2> StorageLocations { get; } public Option2(string feature, string name, T defaultValue) : this(feature, name, defaultValue, storageLocations: Array.Empty<OptionStorageLocation2>()) { } public Option2(string feature, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) : this(feature, group: OptionGroup.Default, name, defaultValue, storageLocations) { } internal Option2(string feature, OptionGroup group, string name, T defaultValue, params OptionStorageLocation2[] storageLocations) : this(feature, group, name, defaultValue, storageLocations.ToImmutableArray()) { } internal Option2(string feature, OptionGroup group, string name, T defaultValue, ImmutableArray<OptionStorageLocation2> storageLocations) { if (string.IsNullOrWhiteSpace(feature)) { throw new ArgumentNullException(nameof(feature)); } if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException(nameof(name)); } OptionDefinition = new OptionDefinition(feature, group, name, defaultValue, typeof(T), isPerLanguage: false); this.StorageLocations = storageLocations; } #if CODE_STYLE object? IOption2.DefaultValue => this.DefaultValue; bool IOption2.IsPerLanguage => false; #else object? IOption.DefaultValue => this.DefaultValue; bool IOption.IsPerLanguage => false; ImmutableArray<OptionStorageLocation> IOption.StorageLocations => this.StorageLocations.As<OptionStorageLocation>(); #endif OptionGroup IOptionWithGroup.Group => this.Group; OptionDefinition IOption2.OptionDefinition => OptionDefinition; public override string ToString() => OptionDefinition.ToString(); public override int GetHashCode() => OptionDefinition.GetHashCode(); public override bool Equals(object? obj) => Equals(obj as IOption2); public bool Equals(IOption2? other) { if (ReferenceEquals(this, other)) { return true; } return OptionDefinition == other?.OptionDefinition; } public static implicit operator OptionKey2(Option2<T> option) => new(option); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Workspace/VisualStudioRemoteHostClientShutdownCancellationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IRemoteHostClientShutdownCancellationService), ServiceLayer.Host), Shared] internal sealed class VisualStudioRemoteHostClientShutdownCancellationService : IRemoteHostClientShutdownCancellationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioRemoteHostClientShutdownCancellationService() { } public CancellationToken ShutdownToken => VsShellUtilities.ShutdownToken; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IRemoteHostClientShutdownCancellationService), ServiceLayer.Host), Shared] internal sealed class VisualStudioRemoteHostClientShutdownCancellationService : IRemoteHostClientShutdownCancellationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioRemoteHostClientShutdownCancellationService() { } public CancellationToken ShutdownToken => VsShellUtilities.ShutdownToken; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicExpressionEvaluator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicExpressionEvaluator : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicExpressionEvaluator(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync(); VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@"Imports System Module Module1 Sub Main() Dim mySByte As SByte = SByte.MaxValue / 2 Dim myShort As Short = Short.MaxValue / 2 Dim myInt As Integer = Integer.MaxValue / 2 Dim myLong As Long = Long.MaxValue / 2 Dim myByte As Byte = Byte.MaxValue / 2 Dim myUShort As UShort = UShort.MaxValue / 2 Dim myUInt As UInteger = UInteger.MaxValue / 2 Dim myULong As ULong = ULong.MaxValue / 2 Dim myFloat As Single = Single.MaxValue / 2 Dim myDouble As Double = Double.MaxValue / 2 Dim myDecimal As Decimal = Decimal.MaxValue / 2 Dim myChar As Char = ""A""c Dim myBool As Boolean = True Dim myObject As Object = Nothing Dim myString As String = String.Empty Dim myValueType As System.ValueType = myShort Dim myEnum As System.Enum = Nothing Dim myArray As System.Array = Nothing Dim myDelegate As System.Delegate = Nothing Dim myMulticastDelegate As System.MulticastDelegate = Nothing System.Diagnostics.Debugger.Break() End Sub End Module"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void ValidateLocalsWindow() { VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.LocalsWindow.Verify.CheckCount(20); VisualStudio.LocalsWindow.Verify.CheckEntry("mySByte", "SByte", "64"); VisualStudio.LocalsWindow.Verify.CheckEntry("myShort", "Short", "16384"); VisualStudio.LocalsWindow.Verify.CheckEntry("myInt", "Integer", "1073741824"); VisualStudio.LocalsWindow.Verify.CheckEntry("myLong", "Long", "4611686018427387904"); VisualStudio.LocalsWindow.Verify.CheckEntry("myByte", "Byte", "128"); VisualStudio.LocalsWindow.Verify.CheckEntry("myUShort", "UShort", "32768"); VisualStudio.LocalsWindow.Verify.CheckEntry("myUInt", "UInteger", "2147483648"); VisualStudio.LocalsWindow.Verify.CheckEntry("myULong", "ULong", "9223372036854775808"); VisualStudio.LocalsWindow.Verify.CheckEntry("myFloat", "Single", "1.70141173E+38"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDouble", "Double", "8.9884656743115785E+307"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDecimal", "Decimal", "39614081257132168796771975168"); VisualStudio.LocalsWindow.Verify.CheckEntry("myChar", "Char", "\"A\"c"); VisualStudio.LocalsWindow.Verify.CheckEntry("myBool", "Boolean", "True"); VisualStudio.LocalsWindow.Verify.CheckEntry("myObject", "Object", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myString", "String", "\"\""); VisualStudio.LocalsWindow.Verify.CheckEntry("myValueType", "System.ValueType {Short}", "16384"); VisualStudio.LocalsWindow.Verify.CheckEntry("myEnum", "System.Enum", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myArray", "System.Array", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDelegate", "System.Delegate", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myMulticastDelegate", "System.MulticastDelegate", "Nothing"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluatePrimitiveValues() { VisualStudio.Debugger.Go(waitForBreakMode: true); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("myByte", "Byte", "128"); VisualStudio.Debugger.CheckExpression("myFloat", "Single", "1.70141173E+38"); VisualStudio.Debugger.CheckExpression("myChar", "Char", "\"A\"c"); VisualStudio.Debugger.CheckExpression("myObject", "Object", "Nothing"); VisualStudio.Debugger.CheckExpression("myString", "String", "\"\""); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/19526")] public void EvaluateLambdaExpressions() { VisualStudio.Debugger.Go(waitForBreakMode: true); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("(Function(val)(val+val))(1)", "Integer", "2"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluateInvalidExpressions() { VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.Debugger.CheckExpression("myNonsense", "", "error BC30451: 'myNonsense' is not declared. It may be inaccessible due to its protection level."); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void StateMachineTypeParameters() { VisualStudio.Editor.SetText(@" Imports System Imports System.Collections.Generic Module Module1 Sub Main() For Each arg In I({ ""a"", ""b""}) Console.WriteLine(arg) Next End Sub Iterator Function I(Of T)(tt As T()) As IEnumerable(Of T) For Each item In tt Stop Yield item Next End Function End Module "); VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.LocalsWindow.Verify.CheckEntry("Type variables", "", ""); VisualStudio.LocalsWindow.Verify.CheckEntry(new string[] { "Type variables", "T" }, "String", "String"); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("GetType(T) = GetType(String)", "Boolean", "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; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicExpressionEvaluator : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicExpressionEvaluator(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync(); VisualStudio.SolutionExplorer.CreateSolution(nameof(BasicBuild)); var testProj = new ProjectUtils.Project("TestProj"); VisualStudio.SolutionExplorer.AddProject(testProj, WellKnownProjectTemplates.ConsoleApplication, LanguageNames.VisualBasic); VisualStudio.Editor.SetText(@"Imports System Module Module1 Sub Main() Dim mySByte As SByte = SByte.MaxValue / 2 Dim myShort As Short = Short.MaxValue / 2 Dim myInt As Integer = Integer.MaxValue / 2 Dim myLong As Long = Long.MaxValue / 2 Dim myByte As Byte = Byte.MaxValue / 2 Dim myUShort As UShort = UShort.MaxValue / 2 Dim myUInt As UInteger = UInteger.MaxValue / 2 Dim myULong As ULong = ULong.MaxValue / 2 Dim myFloat As Single = Single.MaxValue / 2 Dim myDouble As Double = Double.MaxValue / 2 Dim myDecimal As Decimal = Decimal.MaxValue / 2 Dim myChar As Char = ""A""c Dim myBool As Boolean = True Dim myObject As Object = Nothing Dim myString As String = String.Empty Dim myValueType As System.ValueType = myShort Dim myEnum As System.Enum = Nothing Dim myArray As System.Array = Nothing Dim myDelegate As System.Delegate = Nothing Dim myMulticastDelegate As System.MulticastDelegate = Nothing System.Diagnostics.Debugger.Break() End Sub End Module"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void ValidateLocalsWindow() { VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.LocalsWindow.Verify.CheckCount(20); VisualStudio.LocalsWindow.Verify.CheckEntry("mySByte", "SByte", "64"); VisualStudio.LocalsWindow.Verify.CheckEntry("myShort", "Short", "16384"); VisualStudio.LocalsWindow.Verify.CheckEntry("myInt", "Integer", "1073741824"); VisualStudio.LocalsWindow.Verify.CheckEntry("myLong", "Long", "4611686018427387904"); VisualStudio.LocalsWindow.Verify.CheckEntry("myByte", "Byte", "128"); VisualStudio.LocalsWindow.Verify.CheckEntry("myUShort", "UShort", "32768"); VisualStudio.LocalsWindow.Verify.CheckEntry("myUInt", "UInteger", "2147483648"); VisualStudio.LocalsWindow.Verify.CheckEntry("myULong", "ULong", "9223372036854775808"); VisualStudio.LocalsWindow.Verify.CheckEntry("myFloat", "Single", "1.70141173E+38"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDouble", "Double", "8.9884656743115785E+307"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDecimal", "Decimal", "39614081257132168796771975168"); VisualStudio.LocalsWindow.Verify.CheckEntry("myChar", "Char", "\"A\"c"); VisualStudio.LocalsWindow.Verify.CheckEntry("myBool", "Boolean", "True"); VisualStudio.LocalsWindow.Verify.CheckEntry("myObject", "Object", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myString", "String", "\"\""); VisualStudio.LocalsWindow.Verify.CheckEntry("myValueType", "System.ValueType {Short}", "16384"); VisualStudio.LocalsWindow.Verify.CheckEntry("myEnum", "System.Enum", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myArray", "System.Array", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myDelegate", "System.Delegate", "Nothing"); VisualStudio.LocalsWindow.Verify.CheckEntry("myMulticastDelegate", "System.MulticastDelegate", "Nothing"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluatePrimitiveValues() { VisualStudio.Debugger.Go(waitForBreakMode: true); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("myByte", "Byte", "128"); VisualStudio.Debugger.CheckExpression("myFloat", "Single", "1.70141173E+38"); VisualStudio.Debugger.CheckExpression("myChar", "Char", "\"A\"c"); VisualStudio.Debugger.CheckExpression("myObject", "Object", "Nothing"); VisualStudio.Debugger.CheckExpression("myString", "String", "\"\""); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/19526")] public void EvaluateLambdaExpressions() { VisualStudio.Debugger.Go(waitForBreakMode: true); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("(Function(val)(val+val))(1)", "Integer", "2"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void EvaluateInvalidExpressions() { VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.Debugger.CheckExpression("myNonsense", "", "error BC30451: 'myNonsense' is not declared. It may be inaccessible due to its protection level."); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/35965")] public void StateMachineTypeParameters() { VisualStudio.Editor.SetText(@" Imports System Imports System.Collections.Generic Module Module1 Sub Main() For Each arg In I({ ""a"", ""b""}) Console.WriteLine(arg) Next End Sub Iterator Function I(Of T)(tt As T()) As IEnumerable(Of T) For Each item In tt Stop Yield item Next End Function End Module "); VisualStudio.Debugger.Go(waitForBreakMode: true); VisualStudio.LocalsWindow.Verify.CheckEntry("Type variables", "", ""); VisualStudio.LocalsWindow.Verify.CheckEntry(new string[] { "Type variables", "T" }, "String", "String"); // It is better to use the Immediate Window but DTE does not provide an access to it. VisualStudio.Debugger.CheckExpression("GetType(T) = GetType(String)", "Boolean", "True"); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/TemporaryStorage/TemporaryStorageServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryStorageServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? (ITemporaryStorageService)new TemporaryStorageService(textFactory) : TrivialTemporaryStorageService.Instance; } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { /// <summary> /// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other /// storage units. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long SingleFileThreshold = 128 * 1024; /// <summary> /// The size in bytes of a memory mapped file created to store multiple temporary objects. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long MultiFileBlockSize = SingleFileThreshold * 32; private readonly ITextFactoryService _textFactory; /// <summary> /// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks /// of each field). /// </summary> /// <remarks> /// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is /// available in source control history. The use of exclusive locks was not causing any measurable /// performance overhead even on 28-thread machines at the time this was written.</para> /// </remarks> private readonly object _gate = new(); /// <summary> /// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer /// allocation until space is no longer available in it. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference; /// <summary>The name of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private string? _name; /// <summary>The total size of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _fileSize; /// <summary> /// The offset into the current memory mapped file where the next storage unit can be held. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _offset; public TemporaryStorageService(ITextFactoryService textFactory) => _textFactory = textFactory; public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) => new TemporaryTextStorage(this); public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken) => new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding); public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) => new TemporaryStreamStorage(this); public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken) => new TemporaryStreamStorage(this, storageName, offset, size); /// <summary> /// Allocate shared storage of a specified size. /// </summary> /// <remarks> /// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual /// storage units. Larger requests are allocated in their own memory mapped files.</para> /// </remarks> /// <param name="size">The size of the shared storage block to allocate.</param> /// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns> private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable<MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return new MemoryMappedInfo(reference, _name, offset: 0, size: size); } else { // Reserve additional space in the existing storage location Contract.ThrowIfNull(_name); _offset += size; return new MemoryMappedInfo(reference, _name, _offset - size, size); } } } public static string CreateUniqueName(long size) => "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N"); private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName { private readonly TemporaryStorageService _service; private SourceHashAlgorithm _checksumAlgorithm; private Encoding? _encoding; private ImmutableArray<byte> _checksum; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) => _service = service; public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding) { _service = service; _checksumAlgorithm = checksumAlgorithm; _encoding = encoding; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: cleanup https://github.com/dotnet/roslyn/issues/43037 // Offet, Size not accessed if Name is null public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm; public Encoding? Encoding => _encoding; public ImmutableArray<byte> GetChecksum() { if (_checksum.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum()); } return _checksum; } public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; _encoding = null; } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using var stream = _memoryMappedInfo.CreateReadableStream(); using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length); // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _checksumAlgorithm = text.ChecksumAlgorithm; _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service.CreateTemporaryStorage(size); // Write the source text out as Unicode. We expect that to be cheap. using var stream = _memoryMappedInfo.CreateWritableStream(); using var writer = new StreamWriter(stream, Encoding.Unicode); text.Write(writer, cancellationToken); } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength) { var src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) => _service = service; public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size) { _service = service; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: clean up https://github.com/dotnet/roslyn/issues/43037 // Offset, Size is only used when Name is not null. public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default) => WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service.CreateTemporaryStorage(size); using var viewStream = _memoryMappedInfo.CreateWritableStream(); var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { RoslynDebug.Assert(src != null); RoslynDebug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host { [ExportWorkspaceServiceFactory(typeof(ITemporaryStorageService), ServiceLayer.Default), Shared] internal partial class TemporaryStorageServiceFactory : IWorkspaceServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryStorageServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { var textFactory = workspaceServices.GetRequiredService<ITextFactoryService>(); // MemoryMapped files which are used by the TemporaryStorageService are present in .NET Framework (including Mono) // and .NET Core Windows. For non-Windows .NET Core scenarios, we can return the TrivialTemporaryStorageService // until https://github.com/dotnet/runtime/issues/30878 is fixed. return PlatformInformation.IsWindows || PlatformInformation.IsRunningOnMono ? (ITemporaryStorageService)new TemporaryStorageService(textFactory) : TrivialTemporaryStorageService.Instance; } /// <summary> /// Temporarily stores text and streams in memory mapped files. /// </summary> internal class TemporaryStorageService : ITemporaryStorageService2 { /// <summary> /// The maximum size in bytes of a single storage unit in a memory mapped file which is shared with other /// storage units. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long SingleFileThreshold = 128 * 1024; /// <summary> /// The size in bytes of a memory mapped file created to store multiple temporary objects. /// </summary> /// <remarks> /// <para>This value was arbitrarily chosen and appears to work well. Can be changed if data suggests /// something better.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private const long MultiFileBlockSize = SingleFileThreshold * 32; private readonly ITextFactoryService _textFactory; /// <summary> /// The synchronization object for accessing the memory mapped file related fields (indicated in the remarks /// of each field). /// </summary> /// <remarks> /// <para>PERF DEV NOTE: A concurrent (but complex) implementation of this type with identical semantics is /// available in source control history. The use of exclusive locks was not causing any measurable /// performance overhead even on 28-thread machines at the time this was written.</para> /// </remarks> private readonly object _gate = new(); /// <summary> /// The most recent memory mapped file for creating multiple storage units. It will be used via bump-pointer /// allocation until space is no longer available in it. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> private ReferenceCountedDisposable<MemoryMappedFile>.WeakReference _weakFileReference; /// <summary>The name of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private string? _name; /// <summary>The total size of the current memory mapped file for multiple storage units.</summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _fileSize; /// <summary> /// The offset into the current memory mapped file where the next storage unit can be held. /// </summary> /// <remarks> /// <para>Access should be synchronized on <see cref="_gate"/>.</para> /// </remarks> /// <seealso cref="_weakFileReference"/> private long _offset; public TemporaryStorageService(ITextFactoryService textFactory) => _textFactory = textFactory; public ITemporaryTextStorage CreateTemporaryTextStorage(CancellationToken cancellationToken) => new TemporaryTextStorage(this); public ITemporaryTextStorage AttachTemporaryTextStorage(string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding, CancellationToken cancellationToken) => new TemporaryTextStorage(this, storageName, offset, size, checksumAlgorithm, encoding); public ITemporaryStreamStorage CreateTemporaryStreamStorage(CancellationToken cancellationToken) => new TemporaryStreamStorage(this); public ITemporaryStreamStorage AttachTemporaryStreamStorage(string storageName, long offset, long size, CancellationToken cancellationToken) => new TemporaryStreamStorage(this, storageName, offset, size); /// <summary> /// Allocate shared storage of a specified size. /// </summary> /// <remarks> /// <para>"Small" requests are fulfilled from oversized memory mapped files which support several individual /// storage units. Larger requests are allocated in their own memory mapped files.</para> /// </remarks> /// <param name="size">The size of the shared storage block to allocate.</param> /// <returns>A <see cref="MemoryMappedInfo"/> describing the allocated block.</returns> private MemoryMappedInfo CreateTemporaryStorage(long size) { if (size >= SingleFileThreshold) { // Larger blocks are allocated separately var mapName = CreateUniqueName(size); var storage = MemoryMappedFile.CreateNew(mapName, size); return new MemoryMappedInfo(new ReferenceCountedDisposable<MemoryMappedFile>(storage), mapName, offset: 0, size: size); } lock (_gate) { // Obtain a reference to the memory mapped file, creating one if necessary. If a reference counted // handle to a memory mapped file is obtained in this section, it must either be disposed before // returning or returned to the caller who will own it through the MemoryMappedInfo. var reference = _weakFileReference.TryAddReference(); if (reference == null || _offset + size > _fileSize) { var mapName = CreateUniqueName(MultiFileBlockSize); var file = MemoryMappedFile.CreateNew(mapName, MultiFileBlockSize); reference = new ReferenceCountedDisposable<MemoryMappedFile>(file); _weakFileReference = new ReferenceCountedDisposable<MemoryMappedFile>.WeakReference(reference); _name = mapName; _fileSize = MultiFileBlockSize; _offset = size; return new MemoryMappedInfo(reference, _name, offset: 0, size: size); } else { // Reserve additional space in the existing storage location Contract.ThrowIfNull(_name); _offset += size; return new MemoryMappedInfo(reference, _name, _offset - size, size); } } } public static string CreateUniqueName(long size) => "Roslyn Temp Storage " + size.ToString() + " " + Guid.NewGuid().ToString("N"); private sealed class TemporaryTextStorage : ITemporaryTextStorage, ITemporaryTextStorageWithName { private readonly TemporaryStorageService _service; private SourceHashAlgorithm _checksumAlgorithm; private Encoding? _encoding; private ImmutableArray<byte> _checksum; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryTextStorage(TemporaryStorageService service) => _service = service; public TemporaryTextStorage(TemporaryStorageService service, string storageName, long offset, long size, SourceHashAlgorithm checksumAlgorithm, Encoding? encoding) { _service = service; _checksumAlgorithm = checksumAlgorithm; _encoding = encoding; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: cleanup https://github.com/dotnet/roslyn/issues/43037 // Offet, Size not accessed if Name is null public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public SourceHashAlgorithm ChecksumAlgorithm => _checksumAlgorithm; public Encoding? Encoding => _encoding; public ImmutableArray<byte> GetChecksum() { if (_checksum.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _checksum, ReadText(CancellationToken.None).GetChecksum()); } return _checksum; } public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; _encoding = null; } public SourceText ReadText(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadText, cancellationToken)) { using var stream = _memoryMappedInfo.CreateReadableStream(); using var reader = CreateTextReaderFromTemporaryStorage((ISupportDirectMemoryAccess)stream, (int)stream.Length); // we pass in encoding we got from original source text even if it is null. return _service._textFactory.CreateText(reader, _encoding, cancellationToken); } } public Task<SourceText> ReadTextAsync(CancellationToken cancellationToken) { // There is a reason for implementing it like this: proper async implementation // that reads the underlying memory mapped file stream in an asynchronous fashion // doesn't actually work. Windows doesn't offer // any non-blocking way to read from a memory mapped file; the underlying memcpy // may block as the memory pages back in and that's something you have to live // with. Therefore, any implementation that attempts to use async will still // always be blocking at least one threadpool thread in the memcpy in the case // of a page fault. Therefore, if we're going to be blocking a thread, we should // just block one thread and do the whole thing at once vs. a fake "async" // implementation which will continue to requeue work back to the thread pool. return Task.Factory.StartNew(() => ReadText(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteText(SourceText text, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteText, cancellationToken)) { _checksumAlgorithm = text.ChecksumAlgorithm; _encoding = text.Encoding; // the method we use to get text out of SourceText uses Unicode (2bytes per char). var size = Encoding.Unicode.GetMaxByteCount(text.Length); _memoryMappedInfo = _service.CreateTemporaryStorage(size); // Write the source text out as Unicode. We expect that to be cheap. using var stream = _memoryMappedInfo.CreateWritableStream(); using var writer = new StreamWriter(stream, Encoding.Unicode); text.Write(writer, cancellationToken); } } public Task WriteTextAsync(SourceText text, CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => WriteText(text, cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } private static unsafe TextReader CreateTextReaderFromTemporaryStorage(ISupportDirectMemoryAccess accessor, int streamLength) { var src = (char*)accessor.GetPointer(); // BOM: Unicode, little endian // Skip the BOM when creating the reader Debug.Assert(*src == 0xFEFF); return new DirectMemoryAccessStreamReader(src + 1, streamLength / sizeof(char) - 1); } } private class TemporaryStreamStorage : ITemporaryStreamStorage, ITemporaryStorageWithName { private readonly TemporaryStorageService _service; private MemoryMappedInfo? _memoryMappedInfo; public TemporaryStreamStorage(TemporaryStorageService service) => _service = service; public TemporaryStreamStorage(TemporaryStorageService service, string storageName, long offset, long size) { _service = service; _memoryMappedInfo = new MemoryMappedInfo(storageName, offset, size); } // TODO: clean up https://github.com/dotnet/roslyn/issues/43037 // Offset, Size is only used when Name is not null. public string? Name => _memoryMappedInfo?.Name; public long Offset => _memoryMappedInfo!.Offset; public long Size => _memoryMappedInfo!.Size; public void Dispose() { // Destructors of SafeHandle and FileStream in MemoryMappedFile // will eventually release resources if this Dispose is not called // explicitly _memoryMappedInfo?.Dispose(); _memoryMappedInfo = null; } public Stream ReadStream(CancellationToken cancellationToken) { if (_memoryMappedInfo == null) { throw new InvalidOperationException(); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_ReadStream, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); return _memoryMappedInfo.CreateReadableStream(); } } public Task<Stream> ReadStreamAsync(CancellationToken cancellationToken = default) { // See commentary in ReadTextAsync for why this is implemented this way. return Task.Factory.StartNew(() => ReadStream(cancellationToken), cancellationToken, TaskCreationOptions.None, TaskScheduler.Default); } public void WriteStream(Stream stream, CancellationToken cancellationToken = default) { // The Wait() here will not actually block, since with useAsync: false, the // entire operation will already be done when WaitStreamMaybeAsync completes. WriteStreamMaybeAsync(stream, useAsync: false, cancellationToken: cancellationToken).GetAwaiter().GetResult(); } public Task WriteStreamAsync(Stream stream, CancellationToken cancellationToken = default) => WriteStreamMaybeAsync(stream, useAsync: true, cancellationToken: cancellationToken); private async Task WriteStreamMaybeAsync(Stream stream, bool useAsync, CancellationToken cancellationToken) { if (_memoryMappedInfo != null) { throw new InvalidOperationException(WorkspacesResources.Temporary_storage_cannot_be_written_more_than_once); } using (Logger.LogBlock(FunctionId.TemporaryStorageServiceFactory_WriteStream, cancellationToken)) { var size = stream.Length; _memoryMappedInfo = _service.CreateTemporaryStorage(size); using var viewStream = _memoryMappedInfo.CreateWritableStream(); var buffer = SharedPools.ByteArray.Allocate(); try { while (true) { int count; if (useAsync) { count = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); } else { count = stream.Read(buffer, 0, buffer.Length); } if (count == 0) { break; } viewStream.Write(buffer, 0, count); } } finally { SharedPools.ByteArray.Free(buffer); } } } } } internal unsafe class DirectMemoryAccessStreamReader : TextReaderWithLength { private char* _position; private readonly char* _end; public DirectMemoryAccessStreamReader(char* src, int length) : base(length) { RoslynDebug.Assert(src != null); RoslynDebug.Assert(length >= 0); _position = src; _end = _position + length; } public override int Peek() { if (_position >= _end) { return -1; } return *_position; } public override int Read() { if (_position >= _end) { return -1; } return *_position++; } public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0 || index >= buffer.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0 || (index + count) > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } count = Math.Min(count, (int)(_end - _position)); if (count > 0) { Marshal.Copy((IntPtr)_position, buffer, index, count); _position += count; } return count; } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/CodeFixes/OrderModifiers/CSharpOrderModifiersCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared] internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider { private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpOrderModifiersCodeFixProvider() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance) { } protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.OrderModifiers), Shared] internal class CSharpOrderModifiersCodeFixProvider : AbstractOrderModifiersCodeFixProvider { private const string CS0267 = nameof(CS0267); // The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or 'void' [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpOrderModifiersCodeFixProvider() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance) { } protected override ImmutableArray<string> FixableCompilerErrorIds { get; } = ImmutableArray.Create(CS0267); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/EnumerableExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public static class EnumerableExtensions { public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector) { int i = 0; foreach (var item in items) { yield return selector(item, i++); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { public static class EnumerableExtensions { public static IEnumerable<S> SelectWithIndex<T, S>(this IEnumerable<T> items, Func<T, int, S> selector) { int i = 0; foreach (var item in items) { yield return selector(item, i++); } } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItem.BrowseObject.cs
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratedFileItem { private class BrowseObject : LocalizableProperties { private readonly SourceGeneratedFileItem _sourceGeneratedFileItem; public BrowseObject(SourceGeneratedFileItem sourceGeneratedFileItem) { this._sourceGeneratedFileItem = sourceGeneratedFileItem; } [BrowseObjectDisplayName(nameof(SolutionExplorerShim.Name))] public string Name => _sourceGeneratedFileItem.HintName; public override string GetClassName() => SolutionExplorerShim.Source_Generated_File_Properties; public override string GetComponentName() => _sourceGeneratedFileItem.HintName; } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratedFileItem { private class BrowseObject : LocalizableProperties { private readonly SourceGeneratedFileItem _sourceGeneratedFileItem; public BrowseObject(SourceGeneratedFileItem sourceGeneratedFileItem) { this._sourceGeneratedFileItem = sourceGeneratedFileItem; } [BrowseObjectDisplayName(nameof(SolutionExplorerShim.Name))] public string Name => _sourceGeneratedFileItem.HintName; public override string GetClassName() => SolutionExplorerShim.Source_Generated_File_Properties; public override string GetComponentName() => _sourceGeneratedFileItem.HintName; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Symbols/Attributes/CommonAttributeDataComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Used to determine if two <see cref="AttributeData"/> instances are identical, /// i.e. they have the same attribute type, attribute constructor and have identical arguments. /// </summary> internal sealed class CommonAttributeDataComparer : IEqualityComparer<AttributeData> { public static CommonAttributeDataComparer Instance = new CommonAttributeDataComparer(); private CommonAttributeDataComparer() { } public bool Equals(AttributeData attr1, AttributeData attr2) { Debug.Assert(attr1 != null); Debug.Assert(attr2 != null); return attr1.AttributeClass == attr2.AttributeClass && attr1.AttributeConstructor == attr2.AttributeConstructor && attr1.HasErrors == attr2.HasErrors && attr1.IsConditionallyOmitted == attr2.IsConditionallyOmitted && attr1.CommonConstructorArguments.SequenceEqual(attr2.CommonConstructorArguments) && attr1.NamedArguments.SequenceEqual(attr2.NamedArguments); } public int GetHashCode(AttributeData attr) { Debug.Assert(attr != null); int hash = attr.AttributeClass?.GetHashCode() ?? 0; hash = attr.AttributeConstructor != null ? Hash.Combine(attr.AttributeConstructor.GetHashCode(), hash) : hash; hash = Hash.Combine(attr.HasErrors, hash); hash = Hash.Combine(attr.IsConditionallyOmitted, hash); hash = Hash.Combine(GetHashCodeForConstructorArguments(attr.CommonConstructorArguments), hash); hash = Hash.Combine(GetHashCodeForNamedArguments(attr.NamedArguments), hash); return hash; } private static int GetHashCodeForConstructorArguments(ImmutableArray<TypedConstant> constructorArguments) { int hash = 0; foreach (var arg in constructorArguments) { hash = Hash.Combine(arg.GetHashCode(), hash); } return hash; } private static int GetHashCodeForNamedArguments(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) { int hash = 0; foreach (var arg in namedArguments) { if (arg.Key != null) { hash = Hash.Combine(arg.Key.GetHashCode(), hash); } hash = Hash.Combine(arg.Value.GetHashCode(), hash); } return hash; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Used to determine if two <see cref="AttributeData"/> instances are identical, /// i.e. they have the same attribute type, attribute constructor and have identical arguments. /// </summary> internal sealed class CommonAttributeDataComparer : IEqualityComparer<AttributeData> { public static CommonAttributeDataComparer Instance = new CommonAttributeDataComparer(); private CommonAttributeDataComparer() { } public bool Equals(AttributeData attr1, AttributeData attr2) { Debug.Assert(attr1 != null); Debug.Assert(attr2 != null); return attr1.AttributeClass == attr2.AttributeClass && attr1.AttributeConstructor == attr2.AttributeConstructor && attr1.HasErrors == attr2.HasErrors && attr1.IsConditionallyOmitted == attr2.IsConditionallyOmitted && attr1.CommonConstructorArguments.SequenceEqual(attr2.CommonConstructorArguments) && attr1.NamedArguments.SequenceEqual(attr2.NamedArguments); } public int GetHashCode(AttributeData attr) { Debug.Assert(attr != null); int hash = attr.AttributeClass?.GetHashCode() ?? 0; hash = attr.AttributeConstructor != null ? Hash.Combine(attr.AttributeConstructor.GetHashCode(), hash) : hash; hash = Hash.Combine(attr.HasErrors, hash); hash = Hash.Combine(attr.IsConditionallyOmitted, hash); hash = Hash.Combine(GetHashCodeForConstructorArguments(attr.CommonConstructorArguments), hash); hash = Hash.Combine(GetHashCodeForNamedArguments(attr.NamedArguments), hash); return hash; } private static int GetHashCodeForConstructorArguments(ImmutableArray<TypedConstant> constructorArguments) { int hash = 0; foreach (var arg in constructorArguments) { hash = Hash.Combine(arg.GetHashCode(), hash); } return hash; } private static int GetHashCodeForNamedArguments(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) { int hash = 0; foreach (var arg in namedArguments) { if (arg.Key != null) { hash = Hash.Combine(arg.Key.GetHashCode(), hash); } hash = Hash.Combine(arg.Value.GetHashCode(), hash); } return hash; } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharp/Navigation/FSharpDocumentNavigationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { [ExportWorkspaceService(typeof(IFSharpDocumentNavigationService)), Shared] internal class FSharpDocumentNavigationService : IFSharpDocumentNavigationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpDocumentNavigationService() { } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => CanNavigateToSpan(workspace, documentId, textSpan, CancellationToken.None); public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, CancellationToken.None); public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, cancellationToken); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace) => CanNavigateToPosition(workspace, documentId, position, virtualSpace, CancellationToken.None); public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) => TryNavigateToSpan(workspace, documentId, textSpan, options, CancellationToken.None); public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToSpan(workspace, documentId, textSpan, options, cancellationToken); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) => TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, CancellationToken.None); public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, cancellationToken); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) => TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Navigation { [ExportWorkspaceService(typeof(IFSharpDocumentNavigationService)), Shared] internal class FSharpDocumentNavigationService : IFSharpDocumentNavigationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpDocumentNavigationService() { } public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) => CanNavigateToSpan(workspace, documentId, textSpan, CancellationToken.None); public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToSpan(workspace, documentId, textSpan, cancellationToken); } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) => CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, CancellationToken.None); public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, cancellationToken); } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace) => CanNavigateToPosition(workspace, documentId, position, virtualSpace, CancellationToken.None); public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.CanNavigateToPosition(workspace, documentId, position, virtualSpace, cancellationToken); } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) => TryNavigateToSpan(workspace, documentId, textSpan, options, CancellationToken.None); public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToSpan(workspace, documentId, textSpan, options, cancellationToken); } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) => TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, CancellationToken.None); public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToLineAndOffset(workspace, documentId, lineNumber, offset, options, cancellationToken); } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) => TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, CancellationToken.None); public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options, CancellationToken cancellationToken) { var service = workspace.Services.GetService<IDocumentNavigationService>(); return service.TryNavigateToPosition(workspace, documentId, position, virtualSpace, options, cancellationToken); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/BraceMatching/ClassificationTypeDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal sealed class ClassificationTypeDefinitions { public const string BraceMatchingName = "brace matching"; [Export] [Name(BraceMatchingName)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition BraceMatching; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching { internal sealed class ClassificationTypeDefinitions { public const string BraceMatchingName = "brace matching"; [Export] [Name(BraceMatchingName)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition BraceMatching; } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Lsif/Generator/ResultSetTracking/IResultSetTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking { /// <summary> /// An object that tracks a mapping from symbols to the result sets that have information about those symbols. /// </summary> internal interface IResultSetTracker { Id<ResultSet> GetResultSetIdForSymbol(ISymbol symbol); Id<T> GetResultIdForSymbol<T>(ISymbol symbol, string edgeKind, Func<T> vertexCreator) where T : Vertex; bool ResultSetNeedsInformationalEdgeAdded(ISymbol symbol, string edgeKind); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.ResultSetTracking { /// <summary> /// An object that tracks a mapping from symbols to the result sets that have information about those symbols. /// </summary> internal interface IResultSetTracker { Id<ResultSet> GetResultSetIdForSymbol(ISymbol symbol); Id<T> GetResultIdForSymbol<T>(ISymbol symbol, string edgeKind, Func<T> vertexCreator) where T : Vertex; bool ResultSetNeedsInformationalEdgeAdded(ISymbol symbol, string edgeKind); } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Symbols/EnumTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class EnumTests : CSharpTestBase { // Common example. (Associated Dev10 errors are indicated for cases // where the underlying type of the enum cannot be determined.) private const string ExampleSource = @"class C { static void F(E e) { } static void Main() { E e = E.A; // Dev10: 'E.A' is not supported by the language F(e); // Dev10: no error F(E.B); // Dev10: 'E.B' is not supported by the language int b = (int)e; // Dev10: cannot convert 'E' to 'int' e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' } }"; [ClrOnlyFact] public void EnumWithPrivateInstanceField() { // No errors. CompileWithCustomILSource( ExampleSource, @".class public E extends [mscorlib]System.Enum { .field private specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(31) .field public static literal valuetype E B = int16(32) }"); } [Fact] public void EnumWithNoInstanceFields() { EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithMultipleInstanceFields() { // Note that Dev10 reports a single error for this case: // "'E' is a type not supported by the language" for "static void F(E e) { }" EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 _val1 .field public specialname rtspecialname int32 _val2 .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithPrivateLiterals() { CreateCompilationWithILAndMscorlib40( @"class C { static void F(E e) { } static void Main() { F(E.A); F(E.B); F(E.C); } }", @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(0) .field private static literal valuetype E B = int16(1) .field assembly static literal valuetype E C = int16(2) }").VerifyDiagnostics( // (7,13): error CS0117: 'E' does not contain a definition for 'B' // F(E.B); Diagnostic(ErrorCode.ERR_NoSuchMember, "B").WithArguments("E", "B"), // (8,13): error CS0117: 'E' does not contain a definition for 'C' // F(E.C); Diagnostic(ErrorCode.ERR_NoSuchMember, "C").WithArguments("E", "C")); } [Fact] public void EnumUnsupportedUnderlyingType() { // bool EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname bool value__ .field public static literal valuetype E A = bool(false) .field public static literal valuetype E B = bool(true) }"); // char EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname char value__ .field public static literal valuetype E A = char(0) .field public static literal valuetype E B = char(1) }"); // string EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname string _val .field public static literal valuetype E A = int16(0) .field public static literal valuetype E B = int16(1) }"); } private void EnumWithBogusUnderlyingType(string ilSource) { CreateCompilationWithILAndMscorlib40(ExampleSource, ilSource).VerifyDiagnostics( // (6,15): error CS0570: 'E.A' is not supported by the language // E e = E.A; // Dev10: 'E.A' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.A").WithArguments("E.A"), // (8,11): error CS0570: 'E.B' is not supported by the language // F(E.B); // Dev10: 'E.B' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.B").WithArguments("E.B"), // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'E' and 'int' // e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' Diagnostic(ErrorCode.ERR_BadBinaryOps, "e + 1").WithArguments("+", "E", "int"), // (11,13): error CS0023: Operator '~' cannot be applied to operand of type 'E' // e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' Diagnostic(ErrorCode.ERR_BadUnaryOp, "~e").WithArguments("~", "E")); } [Fact] public void CycleOneMember() { var source = @"enum E { A = A, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CycleTwoMembers() { var source = @"enum E { A = B + 1, B = A + 1, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void TwoConnectedCycles() { var source = @"enum E { A = B | C, B = A + 1, C = A + 2, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B | C, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CyclesAndConnectedFields() { var source = @"enum E { A = A | B, B = C, C = D, D = D }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A | B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (6,5): error CS0110: The evaluation of the constant value for 'E.D' involves a circular definition // D = D Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("E.D").WithLocation(6, 5)); } [Fact] public void DependenciesTwoEnums() { var source = @"enum E { A = F.A, B = F.B + A } enum F { A = 1, B = E.A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void MultipleCircularDependencies() { var source = @"enum E { A = B + F.B, B = A + F.A, } enum F { A = E.B + 1, B = A + 1, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + F.B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (4,5): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // B = A + F.A, Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(4, 5)); } [Fact] public void CircularDefinitionManyMembers_Implicit() { // enum E { M0 = Mn + 1, M1, ..., Mn, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~5600 members. var source = GenerateEnum(10000, (i, n) => (i == 0) ? string.Format("M{0} + 1", n - 1) : ""); CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M5999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843037")] [ConditionalFact(typeof(NoIOperationValidation))] public void CircularDefinitionManyMembers_Explicit() { // enum E { M0 = Mn + 1, M1 = M0 + 1, ..., Mn = Mn-1 + 1, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1600 members. var source = GenerateEnum(10000, (i, n) => string.Format("M{0} + 1", (i == 0) ? (n - 1) : (i - 1))); CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M1999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843037")] [ConditionalFact(typeof(NoIOperationValidation))] public void InvertedDefinitionManyMembers_Explicit() { // enum E { M0 = M1 - 1, M1 = M2 - 1, ..., Mn = n, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1500 members. var source = GenerateEnum(10000, (i, n) => (i < n - 1) ? string.Format("M{0} - 1", i + 1) : i.ToString()); CreateCompilation(source).VerifyDiagnostics(); } /// <summary> /// Generate "enum E { M0 = ..., M1 = ..., ..., Mn = ... }". /// </summary> private static string GenerateEnum(int n, Func<int, int, string> getMemberValue) { var builder = new StringBuilder(); builder.AppendLine("enum E"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.Append(string.Format(" M{0}", i)); var value = getMemberValue(i, n); if (!string.IsNullOrEmpty(value)) { builder.Append(" = "); builder.Append(value); } builder.AppendLine(","); } builder.AppendLine("}"); return builder.ToString(); } [WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")] [Fact] public void UseSiteError_01() { var sourceA = @"public class A { }"; var comp = CreateCompilation(sourceA, assemblyName: "UseSiteError_sourceA"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B<T> { public enum E { F } } public class C { public const B<A>.E F = default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { const int x = (int)~C.F; System.Console.WriteLine(x); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }); comp.VerifyDiagnostics( // (5,31): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // const int x = (int)~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 31) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.BitwiseNotExpression); var value = model.GetConstantValue(expr); Assert.False(value.HasValue); } [WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")] [Fact] public void UseSiteError_02() { var sourceA = @"public class A { }"; var comp = CreateCompilation(sourceA, assemblyName: "UseSiteError_sourceA"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B<T> { public enum E { F } } public class C { public const B<A>.E F = default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { var x = ~C.F; System.Console.WriteLine(x); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (5,20): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var x = ~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 20) ); comp = CreateCompilation(sourceC, references: new[] { refB }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,20): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var x = ~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 20) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class EnumTests : CSharpTestBase { // Common example. (Associated Dev10 errors are indicated for cases // where the underlying type of the enum cannot be determined.) private const string ExampleSource = @"class C { static void F(E e) { } static void Main() { E e = E.A; // Dev10: 'E.A' is not supported by the language F(e); // Dev10: no error F(E.B); // Dev10: 'E.B' is not supported by the language int b = (int)e; // Dev10: cannot convert 'E' to 'int' e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' } }"; [ClrOnlyFact] public void EnumWithPrivateInstanceField() { // No errors. CompileWithCustomILSource( ExampleSource, @".class public E extends [mscorlib]System.Enum { .field private specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(31) .field public static literal valuetype E B = int16(32) }"); } [Fact] public void EnumWithNoInstanceFields() { EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithMultipleInstanceFields() { // Note that Dev10 reports a single error for this case: // "'E' is a type not supported by the language" for "static void F(E e) { }" EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int32 _val1 .field public specialname rtspecialname int32 _val2 .field public static literal valuetype E A = int32(0) .field public static literal valuetype E B = int32(1) }"); } [Fact] public void EnumWithPrivateLiterals() { CreateCompilationWithILAndMscorlib40( @"class C { static void F(E e) { } static void Main() { F(E.A); F(E.B); F(E.C); } }", @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname int16 _val .field public static literal valuetype E A = int16(0) .field private static literal valuetype E B = int16(1) .field assembly static literal valuetype E C = int16(2) }").VerifyDiagnostics( // (7,13): error CS0117: 'E' does not contain a definition for 'B' // F(E.B); Diagnostic(ErrorCode.ERR_NoSuchMember, "B").WithArguments("E", "B"), // (8,13): error CS0117: 'E' does not contain a definition for 'C' // F(E.C); Diagnostic(ErrorCode.ERR_NoSuchMember, "C").WithArguments("E", "C")); } [Fact] public void EnumUnsupportedUnderlyingType() { // bool EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname bool value__ .field public static literal valuetype E A = bool(false) .field public static literal valuetype E B = bool(true) }"); // char EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname char value__ .field public static literal valuetype E A = char(0) .field public static literal valuetype E B = char(1) }"); // string EnumWithBogusUnderlyingType( @".class public E extends [mscorlib]System.Enum { .field public specialname rtspecialname string _val .field public static literal valuetype E A = int16(0) .field public static literal valuetype E B = int16(1) }"); } private void EnumWithBogusUnderlyingType(string ilSource) { CreateCompilationWithILAndMscorlib40(ExampleSource, ilSource).VerifyDiagnostics( // (6,15): error CS0570: 'E.A' is not supported by the language // E e = E.A; // Dev10: 'E.A' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.A").WithArguments("E.A"), // (8,11): error CS0570: 'E.B' is not supported by the language // F(E.B); // Dev10: 'E.B' is not supported by the language Diagnostic(ErrorCode.ERR_BindToBogus, "E.B").WithArguments("E.B"), // (10,13): error CS0019: Operator '+' cannot be applied to operands of type 'E' and 'int' // e = e + 1; // Dev10: operator '+' cannot be applied to operands of type 'E' and 'int' Diagnostic(ErrorCode.ERR_BadBinaryOps, "e + 1").WithArguments("+", "E", "int"), // (11,13): error CS0023: Operator '~' cannot be applied to operand of type 'E' // e = ~e; // Dev10: operator '~' cannot be applied to operand of type 'E' Diagnostic(ErrorCode.ERR_BadUnaryOp, "~e").WithArguments("~", "E")); } [Fact] public void CycleOneMember() { var source = @"enum E { A = A, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CycleTwoMembers() { var source = @"enum E { A = B + 1, B = A + 1, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void TwoConnectedCycles() { var source = @"enum E { A = B | C, B = A + 1, C = A + 2, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B | C, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5)); } [Fact] public void CyclesAndConnectedFields() { var source = @"enum E { A = A | B, B = C, C = D, D = D }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = A | B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (6,5): error CS0110: The evaluation of the constant value for 'E.D' involves a circular definition // D = D Diagnostic(ErrorCode.ERR_CircConstValue, "D").WithArguments("E.D").WithLocation(6, 5)); } [Fact] public void DependenciesTwoEnums() { var source = @"enum E { A = F.A, B = F.B + A } enum F { A = 1, B = E.A }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void MultipleCircularDependencies() { var source = @"enum E { A = B + F.B, B = A + F.A, } enum F { A = E.B + 1, B = A + 1, }"; CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.A' involves a circular definition // A = B + F.B, Diagnostic(ErrorCode.ERR_CircConstValue, "A").WithArguments("E.A").WithLocation(3, 5), // (4,5): error CS0110: The evaluation of the constant value for 'E.B' involves a circular definition // B = A + F.A, Diagnostic(ErrorCode.ERR_CircConstValue, "B").WithArguments("E.B").WithLocation(4, 5)); } [Fact] public void CircularDefinitionManyMembers_Implicit() { // enum E { M0 = Mn + 1, M1, ..., Mn, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~5600 members. var source = GenerateEnum(10000, (i, n) => (i == 0) ? string.Format("M{0} + 1", n - 1) : ""); CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M5999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843037")] [ConditionalFact(typeof(NoIOperationValidation))] public void CircularDefinitionManyMembers_Explicit() { // enum E { M0 = Mn + 1, M1 = M0 + 1, ..., Mn = Mn-1 + 1, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1600 members. var source = GenerateEnum(10000, (i, n) => string.Format("M{0} + 1", (i == 0) ? (n - 1) : (i - 1))); CreateCompilation(source).VerifyDiagnostics( // (3,5): error CS0110: The evaluation of the constant value for 'E.M0' involves a circular definition // M0 = M1999 + 1, Diagnostic(ErrorCode.ERR_CircConstValue, "M0").WithArguments("E.M0").WithLocation(3, 5)); } [WorkItem(843037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843037")] [ConditionalFact(typeof(NoIOperationValidation))] public void InvertedDefinitionManyMembers_Explicit() { // enum E { M0 = M1 - 1, M1 = M2 - 1, ..., Mn = n, } // Dev12 reports "CS1647: An expression is too long or complex to compile" at ~1500 members. var source = GenerateEnum(10000, (i, n) => (i < n - 1) ? string.Format("M{0} - 1", i + 1) : i.ToString()); CreateCompilation(source).VerifyDiagnostics(); } /// <summary> /// Generate "enum E { M0 = ..., M1 = ..., ..., Mn = ... }". /// </summary> private static string GenerateEnum(int n, Func<int, int, string> getMemberValue) { var builder = new StringBuilder(); builder.AppendLine("enum E"); builder.AppendLine("{"); for (int i = 0; i < n; i++) { builder.Append(string.Format(" M{0}", i)); var value = getMemberValue(i, n); if (!string.IsNullOrEmpty(value)) { builder.Append(" = "); builder.Append(value); } builder.AppendLine(","); } builder.AppendLine("}"); return builder.ToString(); } [WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")] [Fact] public void UseSiteError_01() { var sourceA = @"public class A { }"; var comp = CreateCompilation(sourceA, assemblyName: "UseSiteError_sourceA"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B<T> { public enum E { F } } public class C { public const B<A>.E F = default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { const int x = (int)~C.F; System.Console.WriteLine(x); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }); comp.VerifyDiagnostics( // (5,31): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // const int x = (int)~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 31) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.BitwiseNotExpression); var value = model.GetConstantValue(expr); Assert.False(value.HasValue); } [WorkItem(45625, "https://github.com/dotnet/roslyn/issues/45625")] [Fact] public void UseSiteError_02() { var sourceA = @"public class A { }"; var comp = CreateCompilation(sourceA, assemblyName: "UseSiteError_sourceA"); var refA = comp.EmitToImageReference(); var sourceB = @"public class B<T> { public enum E { F } } public class C { public const B<A>.E F = default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }); var refB = comp.EmitToImageReference(); var sourceC = @"class Program { static void Main() { var x = ~C.F; System.Console.WriteLine(x); } }"; comp = CreateCompilation(sourceC, references: new[] { refB }, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (5,20): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var x = ~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 20) ); comp = CreateCompilation(sourceC, references: new[] { refB }, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,20): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var x = ~C.F; Diagnostic(ErrorCode.ERR_NoTypeDef, "F").WithArguments("A", "UseSiteError_sourceA, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(5, 20) ); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MemberAnalysisResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")] internal struct MemberAnalysisResult { // put these first for better packing public readonly ImmutableArray<Conversion> ConversionsOpt; public readonly ImmutableArray<int> BadArgumentsOpt; public readonly ImmutableArray<int> ArgsToParamsOpt; public readonly ImmutableArray<TypeParameterDiagnosticInfo> ConstraintFailureDiagnostics; public readonly int BadParameter; public readonly MemberResolutionKind Kind; /// <summary> /// Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are invoking a method/property on an instance of a COM imported type. /// This property returns a flag indicating whether we had any ref omitted argument for the given call. /// </summary> public readonly bool HasAnyRefOmittedArgument; private MemberAnalysisResult( MemberResolutionKind kind, ImmutableArray<int> badArgumentsOpt = default, ImmutableArray<int> argsToParamsOpt = default, ImmutableArray<Conversion> conversionsOpt = default, int missingParameter = -1, bool hasAnyRefOmittedArgument = false, ImmutableArray<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt = default) { this.Kind = kind; this.BadArgumentsOpt = badArgumentsOpt; this.ArgsToParamsOpt = argsToParamsOpt; this.ConversionsOpt = conversionsOpt; this.BadParameter = missingParameter; this.HasAnyRefOmittedArgument = hasAnyRefOmittedArgument; this.ConstraintFailureDiagnostics = constraintFailureDiagnosticsOpt.NullToEmpty(); } public override bool Equals(object obj) { throw ExceptionUtilities.Unreachable; } public override int GetHashCode() { throw ExceptionUtilities.Unreachable; } public Conversion ConversionForArg(int arg) { if (this.ConversionsOpt.IsDefault) { return Conversion.Identity; } return this.ConversionsOpt[arg]; } public int ParameterFromArgument(int arg) { Debug.Assert(arg >= 0); if (ArgsToParamsOpt.IsDefault) { return arg; } Debug.Assert(arg < ArgsToParamsOpt.Length); return ArgsToParamsOpt[arg]; } // A method may be applicable, but worse than another method. public bool IsApplicable { get { switch (this.Kind) { case MemberResolutionKind.ApplicableInNormalForm: case MemberResolutionKind.ApplicableInExpandedForm: case MemberResolutionKind.Worse: case MemberResolutionKind.Worst: return true; default: return false; } } } public bool IsValid { get { switch (this.Kind) { case MemberResolutionKind.ApplicableInNormalForm: case MemberResolutionKind.ApplicableInExpandedForm: return true; default: return false; } } } /// <remarks> /// Returns false for <see cref="MemberResolutionKind.UnsupportedMetadata"/> /// because those diagnostics are only reported if no other candidates are /// available. /// </remarks> internal bool HasUseSiteDiagnosticToReportFor(Symbol symbol) { // There is a use site diagnostic to report here, but it is not reported // just because this member was a candidate - only if it "wins". return !SuppressUseSiteDiagnosticsForKind(this.Kind) && (object)symbol != null && symbol.GetUseSiteInfo().DiagnosticInfo != null; } private static bool SuppressUseSiteDiagnosticsForKind(MemberResolutionKind kind) { switch (kind) { case MemberResolutionKind.UnsupportedMetadata: return true; case MemberResolutionKind.NoCorrespondingParameter: case MemberResolutionKind.NoCorrespondingNamedParameter: case MemberResolutionKind.DuplicateNamedArgument: case MemberResolutionKind.NameUsedForPositional: case MemberResolutionKind.RequiredParameterMissing: case MemberResolutionKind.LessDerived: // Dev12 checks all of these things before considering use site diagnostics. // That is, use site diagnostics are suppressed for candidates rejected for these reasons. return true; default: return false; } } public static MemberAnalysisResult ArgumentParameterMismatch(ArgumentAnalysisResult argAnalysis) { switch (argAnalysis.Kind) { case ArgumentAnalysisResultKind.NoCorrespondingParameter: return NoCorrespondingParameter(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.NoCorrespondingNamedParameter: return NoCorrespondingNamedParameter(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.DuplicateNamedArgument: return DuplicateNamedArgument(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.RequiredParameterMissing: return RequiredParameterMissing(argAnalysis.ParameterPosition); case ArgumentAnalysisResultKind.NameUsedForPositional: return NameUsedForPositional(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.BadNonTrailingNamedArgument: return BadNonTrailingNamedArgument(argAnalysis.ArgumentPosition); default: throw ExceptionUtilities.UnexpectedValue(argAnalysis.Kind); } } public static MemberAnalysisResult NameUsedForPositional(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NameUsedForPositional, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult BadNonTrailingNamedArgument(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.BadNonTrailingNamedArgument, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult NoCorrespondingParameter(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NoCorrespondingParameter, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult NoCorrespondingNamedParameter(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NoCorrespondingNamedParameter, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult DuplicateNamedArgument(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.DuplicateNamedArgument, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult RequiredParameterMissing(int parameterPosition) { return new MemberAnalysisResult( MemberResolutionKind.RequiredParameterMissing, missingParameter: parameterPosition); } public static MemberAnalysisResult UseSiteError() { return new MemberAnalysisResult(MemberResolutionKind.UseSiteError); } public static MemberAnalysisResult UnsupportedMetadata() { return new MemberAnalysisResult(MemberResolutionKind.UnsupportedMetadata); } public static MemberAnalysisResult BadArgumentConversions(ImmutableArray<int> argsToParamsOpt, ImmutableArray<int> badArguments, ImmutableArray<Conversion> conversions) { Debug.Assert(conversions.Length != 0); Debug.Assert(badArguments.Length != 0); return new MemberAnalysisResult( MemberResolutionKind.BadArgumentConversion, badArguments, argsToParamsOpt, conversions); } public static MemberAnalysisResult InaccessibleTypeArgument() { return new MemberAnalysisResult(MemberResolutionKind.InaccessibleTypeArgument); } public static MemberAnalysisResult TypeInferenceFailed() { return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceFailed); } public static MemberAnalysisResult TypeInferenceExtensionInstanceArgumentFailed() { return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceExtensionInstanceArgument); } public static MemberAnalysisResult StaticInstanceMismatch() { return new MemberAnalysisResult(MemberResolutionKind.StaticInstanceMismatch); } public static MemberAnalysisResult ConstructedParameterFailedConstraintsCheck(int parameterPosition) { return new MemberAnalysisResult( MemberResolutionKind.ConstructedParameterFailedConstraintCheck, missingParameter: parameterPosition); } public static MemberAnalysisResult WrongRefKind() { return new MemberAnalysisResult(MemberResolutionKind.WrongRefKind); } public static MemberAnalysisResult WrongReturnType() { return new MemberAnalysisResult(MemberResolutionKind.WrongReturnType); } public static MemberAnalysisResult LessDerived() { return new MemberAnalysisResult(MemberResolutionKind.LessDerived); } public static MemberAnalysisResult NormalForm(ImmutableArray<int> argsToParamsOpt, ImmutableArray<Conversion> conversions, bool hasAnyRefOmittedArgument) { return new MemberAnalysisResult(MemberResolutionKind.ApplicableInNormalForm, default(ImmutableArray<int>), argsToParamsOpt, conversions, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument); } public static MemberAnalysisResult ExpandedForm(ImmutableArray<int> argsToParamsOpt, ImmutableArray<Conversion> conversions, bool hasAnyRefOmittedArgument) { return new MemberAnalysisResult(MemberResolutionKind.ApplicableInExpandedForm, default(ImmutableArray<int>), argsToParamsOpt, conversions, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument); } public static MemberAnalysisResult Worse() { return new MemberAnalysisResult(MemberResolutionKind.Worse); } public static MemberAnalysisResult Worst() { return new MemberAnalysisResult(MemberResolutionKind.Worst); } internal static MemberAnalysisResult ConstraintFailure(ImmutableArray<TypeParameterDiagnosticInfo> constraintFailureDiagnostics) { return new MemberAnalysisResult(MemberResolutionKind.ConstraintFailure, constraintFailureDiagnosticsOpt: constraintFailureDiagnostics); } internal static MemberAnalysisResult WrongCallingConvention() { return new MemberAnalysisResult(MemberResolutionKind.WrongCallingConvention); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { [SuppressMessage("Performance", "CA1067", Justification = "Equality not actually implemented")] internal struct MemberAnalysisResult { // put these first for better packing public readonly ImmutableArray<Conversion> ConversionsOpt; public readonly ImmutableArray<int> BadArgumentsOpt; public readonly ImmutableArray<int> ArgsToParamsOpt; public readonly ImmutableArray<TypeParameterDiagnosticInfo> ConstraintFailureDiagnostics; public readonly int BadParameter; public readonly MemberResolutionKind Kind; /// <summary> /// Omit ref feature for COM interop: We can pass arguments by value for ref parameters if we are invoking a method/property on an instance of a COM imported type. /// This property returns a flag indicating whether we had any ref omitted argument for the given call. /// </summary> public readonly bool HasAnyRefOmittedArgument; private MemberAnalysisResult( MemberResolutionKind kind, ImmutableArray<int> badArgumentsOpt = default, ImmutableArray<int> argsToParamsOpt = default, ImmutableArray<Conversion> conversionsOpt = default, int missingParameter = -1, bool hasAnyRefOmittedArgument = false, ImmutableArray<TypeParameterDiagnosticInfo> constraintFailureDiagnosticsOpt = default) { this.Kind = kind; this.BadArgumentsOpt = badArgumentsOpt; this.ArgsToParamsOpt = argsToParamsOpt; this.ConversionsOpt = conversionsOpt; this.BadParameter = missingParameter; this.HasAnyRefOmittedArgument = hasAnyRefOmittedArgument; this.ConstraintFailureDiagnostics = constraintFailureDiagnosticsOpt.NullToEmpty(); } public override bool Equals(object obj) { throw ExceptionUtilities.Unreachable; } public override int GetHashCode() { throw ExceptionUtilities.Unreachable; } public Conversion ConversionForArg(int arg) { if (this.ConversionsOpt.IsDefault) { return Conversion.Identity; } return this.ConversionsOpt[arg]; } public int ParameterFromArgument(int arg) { Debug.Assert(arg >= 0); if (ArgsToParamsOpt.IsDefault) { return arg; } Debug.Assert(arg < ArgsToParamsOpt.Length); return ArgsToParamsOpt[arg]; } // A method may be applicable, but worse than another method. public bool IsApplicable { get { switch (this.Kind) { case MemberResolutionKind.ApplicableInNormalForm: case MemberResolutionKind.ApplicableInExpandedForm: case MemberResolutionKind.Worse: case MemberResolutionKind.Worst: return true; default: return false; } } } public bool IsValid { get { switch (this.Kind) { case MemberResolutionKind.ApplicableInNormalForm: case MemberResolutionKind.ApplicableInExpandedForm: return true; default: return false; } } } /// <remarks> /// Returns false for <see cref="MemberResolutionKind.UnsupportedMetadata"/> /// because those diagnostics are only reported if no other candidates are /// available. /// </remarks> internal bool HasUseSiteDiagnosticToReportFor(Symbol symbol) { // There is a use site diagnostic to report here, but it is not reported // just because this member was a candidate - only if it "wins". return !SuppressUseSiteDiagnosticsForKind(this.Kind) && (object)symbol != null && symbol.GetUseSiteInfo().DiagnosticInfo != null; } private static bool SuppressUseSiteDiagnosticsForKind(MemberResolutionKind kind) { switch (kind) { case MemberResolutionKind.UnsupportedMetadata: return true; case MemberResolutionKind.NoCorrespondingParameter: case MemberResolutionKind.NoCorrespondingNamedParameter: case MemberResolutionKind.DuplicateNamedArgument: case MemberResolutionKind.NameUsedForPositional: case MemberResolutionKind.RequiredParameterMissing: case MemberResolutionKind.LessDerived: // Dev12 checks all of these things before considering use site diagnostics. // That is, use site diagnostics are suppressed for candidates rejected for these reasons. return true; default: return false; } } public static MemberAnalysisResult ArgumentParameterMismatch(ArgumentAnalysisResult argAnalysis) { switch (argAnalysis.Kind) { case ArgumentAnalysisResultKind.NoCorrespondingParameter: return NoCorrespondingParameter(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.NoCorrespondingNamedParameter: return NoCorrespondingNamedParameter(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.DuplicateNamedArgument: return DuplicateNamedArgument(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.RequiredParameterMissing: return RequiredParameterMissing(argAnalysis.ParameterPosition); case ArgumentAnalysisResultKind.NameUsedForPositional: return NameUsedForPositional(argAnalysis.ArgumentPosition); case ArgumentAnalysisResultKind.BadNonTrailingNamedArgument: return BadNonTrailingNamedArgument(argAnalysis.ArgumentPosition); default: throw ExceptionUtilities.UnexpectedValue(argAnalysis.Kind); } } public static MemberAnalysisResult NameUsedForPositional(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NameUsedForPositional, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult BadNonTrailingNamedArgument(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.BadNonTrailingNamedArgument, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult NoCorrespondingParameter(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NoCorrespondingParameter, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult NoCorrespondingNamedParameter(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.NoCorrespondingNamedParameter, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult DuplicateNamedArgument(int argumentPosition) { return new MemberAnalysisResult( MemberResolutionKind.DuplicateNamedArgument, badArgumentsOpt: ImmutableArray.Create<int>(argumentPosition)); } public static MemberAnalysisResult RequiredParameterMissing(int parameterPosition) { return new MemberAnalysisResult( MemberResolutionKind.RequiredParameterMissing, missingParameter: parameterPosition); } public static MemberAnalysisResult UseSiteError() { return new MemberAnalysisResult(MemberResolutionKind.UseSiteError); } public static MemberAnalysisResult UnsupportedMetadata() { return new MemberAnalysisResult(MemberResolutionKind.UnsupportedMetadata); } public static MemberAnalysisResult BadArgumentConversions(ImmutableArray<int> argsToParamsOpt, ImmutableArray<int> badArguments, ImmutableArray<Conversion> conversions) { Debug.Assert(conversions.Length != 0); Debug.Assert(badArguments.Length != 0); return new MemberAnalysisResult( MemberResolutionKind.BadArgumentConversion, badArguments, argsToParamsOpt, conversions); } public static MemberAnalysisResult InaccessibleTypeArgument() { return new MemberAnalysisResult(MemberResolutionKind.InaccessibleTypeArgument); } public static MemberAnalysisResult TypeInferenceFailed() { return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceFailed); } public static MemberAnalysisResult TypeInferenceExtensionInstanceArgumentFailed() { return new MemberAnalysisResult(MemberResolutionKind.TypeInferenceExtensionInstanceArgument); } public static MemberAnalysisResult StaticInstanceMismatch() { return new MemberAnalysisResult(MemberResolutionKind.StaticInstanceMismatch); } public static MemberAnalysisResult ConstructedParameterFailedConstraintsCheck(int parameterPosition) { return new MemberAnalysisResult( MemberResolutionKind.ConstructedParameterFailedConstraintCheck, missingParameter: parameterPosition); } public static MemberAnalysisResult WrongRefKind() { return new MemberAnalysisResult(MemberResolutionKind.WrongRefKind); } public static MemberAnalysisResult WrongReturnType() { return new MemberAnalysisResult(MemberResolutionKind.WrongReturnType); } public static MemberAnalysisResult LessDerived() { return new MemberAnalysisResult(MemberResolutionKind.LessDerived); } public static MemberAnalysisResult NormalForm(ImmutableArray<int> argsToParamsOpt, ImmutableArray<Conversion> conversions, bool hasAnyRefOmittedArgument) { return new MemberAnalysisResult(MemberResolutionKind.ApplicableInNormalForm, default(ImmutableArray<int>), argsToParamsOpt, conversions, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument); } public static MemberAnalysisResult ExpandedForm(ImmutableArray<int> argsToParamsOpt, ImmutableArray<Conversion> conversions, bool hasAnyRefOmittedArgument) { return new MemberAnalysisResult(MemberResolutionKind.ApplicableInExpandedForm, default(ImmutableArray<int>), argsToParamsOpt, conversions, hasAnyRefOmittedArgument: hasAnyRefOmittedArgument); } public static MemberAnalysisResult Worse() { return new MemberAnalysisResult(MemberResolutionKind.Worse); } public static MemberAnalysisResult Worst() { return new MemberAnalysisResult(MemberResolutionKind.Worst); } internal static MemberAnalysisResult ConstraintFailure(ImmutableArray<TypeParameterDiagnosticInfo> constraintFailureDiagnostics) { return new MemberAnalysisResult(MemberResolutionKind.ConstraintFailure, constraintFailureDiagnosticsOpt: constraintFailureDiagnostics); } internal static MemberAnalysisResult WrongCallingConvention() { return new MemberAnalysisResult(MemberResolutionKind.WrongCallingConvention); } } }
-1
dotnet/roslyn
54,986
Fix 'name completion' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:49:22Z
2021-07-20T22:10:40Z
459fff0a5a455ad0232dea6fe886760061aaaedf
4f8eaef1ce57f39088f1bc6af1c3ac301375cb7f
Fix 'name completion' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Navigation/NavigableItemFactory.SymbolLocationNavigableItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal partial class NavigableItemFactory { private class SymbolLocationNavigableItem : INavigableItem { private readonly Solution _solution; private readonly ISymbol _symbol; private readonly Location _location; public SymbolLocationNavigableItem( Solution solution, ISymbol symbol, Location location, ImmutableArray<TaggedText>? displayTaggedParts) { _solution = solution; _symbol = symbol; _location = location; DisplayTaggedParts = displayTaggedParts.GetValueOrDefault(); } public bool DisplayFileLocation => true; public ImmutableArray<TaggedText> DisplayTaggedParts { get; } public Glyph Glyph => _symbol.GetGlyph(); public bool IsImplicitlyDeclared => _symbol.IsImplicitlyDeclared; public Document Document => _location.IsInSource ? _solution.GetDocument(_location.SourceTree) : null; public TextSpan SourceSpan => _location.SourceSpan; public bool IsStale => false; public ImmutableArray<INavigableItem> ChildItems => ImmutableArray<INavigableItem>.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. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal partial class NavigableItemFactory { private class SymbolLocationNavigableItem : INavigableItem { private readonly Solution _solution; private readonly ISymbol _symbol; private readonly Location _location; public SymbolLocationNavigableItem( Solution solution, ISymbol symbol, Location location, ImmutableArray<TaggedText>? displayTaggedParts) { _solution = solution; _symbol = symbol; _location = location; DisplayTaggedParts = displayTaggedParts.GetValueOrDefault(); } public bool DisplayFileLocation => true; public ImmutableArray<TaggedText> DisplayTaggedParts { get; } public Glyph Glyph => _symbol.GetGlyph(); public bool IsImplicitlyDeclared => _symbol.IsImplicitlyDeclared; public Document Document => _location.IsInSource ? _solution.GetDocument(_location.SourceTree) : null; public TextSpan SourceSpan => _location.SourceSpan; public bool IsStale => false; public ImmutableArray<INavigableItem> ChildItems => ImmutableArray<INavigableItem>.Empty; } } }
-1