repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType_PropertyPublicAccessors.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 Partial Friend NotInheritable Class AnonymousTypeManager Private MustInherit Class AnonymousTypePropertyAccessorPublicSymbol Inherits SynthesizedPropertyAccessorBase(Of PropertySymbol) Private ReadOnly _returnType As TypeSymbol Public Sub New([property] As PropertySymbol, returnType As TypeSymbol) MyBase.New([property].ContainingType, [property]) _returnType = returnType End Sub Friend NotOverridable Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class Private NotInheritable Class AnonymousTypePropertyGetAccessorPublicSymbol Inherits AnonymousTypePropertyAccessorPublicSymbol Public Sub New([property] As PropertySymbol) MyBase.New([property], [property].Type) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property End Class Private NotInheritable Class AnonymousTypePropertySetAccessorPublicSymbol Inherits AnonymousTypePropertyAccessorPublicSymbol Private _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New([property] As PropertySymbol, voidTypeSymbol As TypeSymbol) MyBase.New([property], voidTypeSymbol) _parameters = ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, m_propertyOrEvent.Type, 0, False, StringConstants.ValueParameterName)) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet 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 Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Private MustInherit Class AnonymousTypePropertyAccessorPublicSymbol Inherits SynthesizedPropertyAccessorBase(Of PropertySymbol) Private ReadOnly _returnType As TypeSymbol Public Sub New([property] As PropertySymbol, returnType As TypeSymbol) MyBase.New([property].ContainingType, [property]) _returnType = returnType End Sub Friend NotOverridable Overrides ReadOnly Property BackingFieldSymbol As FieldSymbol Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Friend NotOverridable Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function End Class Private NotInheritable Class AnonymousTypePropertyGetAccessorPublicSymbol Inherits AnonymousTypePropertyAccessorPublicSymbol Public Sub New([property] As PropertySymbol) MyBase.New([property], [property].Type) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertyGet End Get End Property End Class Private NotInheritable Class AnonymousTypePropertySetAccessorPublicSymbol Inherits AnonymousTypePropertyAccessorPublicSymbol Private _parameters As ImmutableArray(Of ParameterSymbol) Public Sub New([property] As PropertySymbol, voidTypeSymbol As TypeSymbol) MyBase.New([property], voidTypeSymbol) _parameters = ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, m_propertyOrEvent.Type, 0, False, StringConstants.ValueParameterName)) End Sub Public Overrides ReadOnly Property IsSub As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.PropertySet End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/Structure/BlockStructureOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Structure { internal static class BlockStructureOptions { public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForDeclarationLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForCodeLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCodeLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForCommentsAndPreprocessorRegions = new( nameof(BlockStructureOptions), nameof(ShowOutliningForCommentsAndPreprocessorRegions), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForDeclarationLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowOutliningForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForCodeLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowOutliningForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCodeLevelConstructs)}")); public static readonly PerLanguageOption2<bool> CollapseRegionsWhenCollapsingToDefinitions = new( nameof(BlockStructureOptions), nameof(CollapseRegionsWhenCollapsingToDefinitions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(CollapseRegionsWhenCollapsingToDefinitions)}")); public static readonly PerLanguageOption2<int> MaximumBannerLength = new( nameof(BlockStructureOptions), nameof(MaximumBannerLength), defaultValue: 80, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(MaximumBannerLength)}")); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Structure { internal static class BlockStructureOptions { public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForDeclarationLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowBlockStructureGuidesForCodeLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCodeLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForCommentsAndPreprocessorRegions = new( nameof(BlockStructureOptions), nameof(ShowOutliningForCommentsAndPreprocessorRegions), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForDeclarationLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowOutliningForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption2<bool> ShowOutliningForCodeLevelConstructs = new( nameof(BlockStructureOptions), nameof(ShowOutliningForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCodeLevelConstructs)}")); public static readonly PerLanguageOption2<bool> CollapseRegionsWhenCollapsingToDefinitions = new( nameof(BlockStructureOptions), nameof(CollapseRegionsWhenCollapsingToDefinitions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(CollapseRegionsWhenCollapsingToDefinitions)}")); public static readonly PerLanguageOption2<int> MaximumBannerLength = new( nameof(BlockStructureOptions), nameof(MaximumBannerLength), defaultValue: 80, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(MaximumBannerLength)}")); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/Test2/GoToDefinition/VisualBasicGoToDefinitionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition <[UseExportProvider]> Public Class VisualBasicGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "Normal Visual Basic Tests" <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> public class MyClass1 public property [|Prop1|] as integer end class class Program sub Main() dim instance = new MyClass1() dim x as new With { instance.$$Prop1 } end sub end class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] End Class Class OtherClass Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as Integer = 12$$3 </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as String = "wo$$ow" </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(541105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541105")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicPropertyBackingField() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property [|P|] As Integer Sub M() Me.$$_P = 10 End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Outer Class [|Inner|] End Class Dim obj as In$$ner End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class OtherClass Dim obj As SomeClass End Class </Document> <Document> Class OtherClass2 Dim obj As Some$$Class End Class </Document> <Document> Class [|SomeClass|] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> DummyClass End Class </Document> <Document> Partial Class [|OtherClass|] Dim a As Integer End Class </Document> <Document> Partial Class [|OtherClass|] Dim b As Integer End Class </Document> <Document> Class ConsumingClass Dim obj As Other$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As Some$$Class End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class Customer Private Sub [|OnNameChanged|]() End Sub End Class </Document> <Document> Partial Class Customer Sub New() Dim x As New Customer() x.OnNameChanged$$() End Sub Partial Private Sub OnNameChanged() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchLeft() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As $$SomeClass End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchRight() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMe() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() MyClass.Goo() $$Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() $$MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyBase() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|B|] Sub New() End Sub End Class Class C Inherits B Sub New() $$MyBase.New() MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenSubDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Sub [|Method|]() End Sub End Class Class Derived Inherits Base Overr$$ides Sub Method() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenFunctionDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Function [|Method|]() As Integer Return 1 End Function End Class Class Derived Inherits Base Overr$$ides Function Method() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenPropertyDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Property [|Number|] As Integer End Class Class Derived Inherits Base Overr$$ides Property Number As Integer End Class </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Venus Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> #ExternalSource ("Default.aspx", 1) Class [|Program|] Sub Main(args As String()) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTestThroughExecuteCommand() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim i As String = "1" i.Test$$Ext() End Sub End Class Module Ex <System.Runtime.CompilerServices.Extension()> Public Sub TestExt(Of T)(ex As T) End Sub <System.Runtime.CompilerServices.Extension()> Public Sub [|TestExt|](ex As string) End Sub End Module]]>] </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(543218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543218")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicQueryRangeVariable() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q3 = From [|num|] In arr Select $$num End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoConstant() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$200 [|200|]: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(10132, "https://github.com/dotnet/roslyn/issues/10132")> <WorkItem(545661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545661")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageParameterizedPropertyOverride() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Class A Public Overridable ReadOnly Property X(y As Integer) As Integer [|Get|] End Get End Property End Class </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class B : A { public override int get_X(int y) { return base.$$get_X(y); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageNavigationToVBModuleMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class C { static void N() { A.$$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationVB() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class SomeClass End Class C$$lass OtherClass Dim obj As SomeClass End Class </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(902119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902119")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnInferredFieldInitializer() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class2 Sub Test() Dim var1 = New With {Key .var2 = "Bob", Class2.va$$r3} End Sub Shared Property [|var3|]() As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(885151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/885151")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionGlobalImportAlias() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <CompilationOptions> <GlobalImport>Goo = Importable.ImportMe</GlobalImport> </CompilationOptions> <Document> Public Class Class2 Sub Test() Dim x as Go$$o End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace Importable Public Class [|ImportMe|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Exit() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit$$ Select End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Select() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit Select$$ End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Exit Sub$$ End Sub[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M() As Integer Exit Sub$$ End Function[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue$$ While End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue While$$ End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() While True Exit While$$ End While[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue$$ For Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For index As Integer = 1 To 5 Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For Each element In Nothing Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For Each element In Nothing Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do While True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do While True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Until True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do Until True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopWhile_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop While True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopUntil_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop Until True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTry() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTryInCatch() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Catch Exception Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Partial Sub M() End Sub [||]Partial Private Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Partial Private Sub M() Return$$ End Sub Partial Sub M() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSubLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Sub() Return$$ End Sub End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Function M() As Int Return$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M([|x|] As Integer) As Integer Return x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Iterator Function M() As IEnumerable(Of Integer) Yield$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Iterator Function M([|x|] As Integer) As IEnumerable(Of Integer) Yield x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunctionLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Function() As Int Return$$ 1 End Function End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInConstructor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub New() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInOperator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Shared Operator +(ByVal i As Integer) As Integer Return$$ 1 End Operator End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Return$$ 1 End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Set Return$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Exit Property$$ End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property P() As Integer [||]Set Exit Property$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInAddHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]AddHandler(ByVal value As EventHandler) Return$$ End AddHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRemoveHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RemoveHandler(ByVal value As EventHandler) Return$$ End RemoveHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRaiseEvent() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Return$$ End RaiseEvent End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition <[UseExportProvider]> Public Class VisualBasicGoToDefinitionTests Inherits GoToDefinitionTestsBase #Region "Normal Visual Basic Tests" <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnAnonymousMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> public class MyClass1 public property [|Prop1|] as integer end class class Program sub Main() dim instance = new MyClass1() dim x as new With { instance.$$Prop1 } end sub end class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] End Class Class OtherClass Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as Integer = 12$$3 </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> <WorkItem(23030, "https://github.com/dotnet/roslyn/issues/23030")> Public Sub TestVisualBasicStringLiteralGoToDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Dim x as String = "wo$$ow" </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(541105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541105")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicPropertyBackingField() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property [|P|] As Integer Sub M() Me.$$_P = 10 End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionSameClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionNestedClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Outer Class [|Inner|] End Class Dim obj as In$$ner End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionDifferentFiles() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class OtherClass Dim obj As SomeClass End Class </Document> <Document> Class OtherClass2 Dim obj As Some$$Class End Class </Document> <Document> Class [|SomeClass|] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialClasses() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> DummyClass End Class </Document> <Document> Partial Class [|OtherClass|] Dim a As Integer End Class </Document> <Document> Partial Class [|OtherClass|] Dim b As Integer End Class </Document> <Document> Class ConsumingClass Dim obj As Other$$Class End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As Some$$Class End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoDefinitionPartialMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class Customer Private Sub [|OnNameChanged|]() End Sub End Class </Document> <Document> Partial Class Customer Sub New() Dim x As New Customer() x.OnNameChanged$$() End Sub Partial Private Sub OnNameChanged() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchLeft() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As $$SomeClass End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTouchRight() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMe() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() MyClass.Goo() $$Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyClass() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() $$MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicMyBase() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|B|] Sub New() End Sub End Class Class C Inherits B Sub New() $$MyBase.New() MyClass.Goo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Goo() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenSubDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Sub [|Method|]() End Sub End Class Class Derived Inherits Base Overr$$ides Sub Method() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenFunctionDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Function [|Method|]() As Integer Return 1 End Function End Class Class Derived Inherits Base Overr$$ides Function Method() As Integer Return 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOverridenPropertyDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Base Overridable Property [|Number|] As Integer End Class Class Derived Inherits Base Overr$$ides Property Number As Integer End Class </Document> </Project> </Workspace> Test(workspace) End Sub #End Region #Region "Venus Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicVenusGotoDefinition() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> #ExternalSource ("Default.aspx", 1) Class [|Program|] Sub Main(args As String()) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicFilterGotoDefResultsFromHiddenCodeForUIPresenters() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicDoNotFilterGotoDefResultsFromHiddenCodeForApis() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicTestThroughExecuteCommand() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub goo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToDefinitionOnExtensionMethod() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim i As String = "1" i.Test$$Ext() End Sub End Class Module Ex <System.Runtime.CompilerServices.Extension()> Public Sub TestExt(Of T)(ex As T) End Sub <System.Runtime.CompilerServices.Extension()> Public Sub [|TestExt|](ex As string) End Sub End Module]]>] </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(543218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543218")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicQueryRangeVariable() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q3 = From [|num|] In arr Select $$num End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGotoConstant() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$200 [|200|]: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(10132, "https://github.com/dotnet/roslyn/issues/10132")> <WorkItem(545661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545661")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageParameterizedPropertyOverride() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Class A Public Overridable ReadOnly Property X(y As Integer) As Integer [|Get|] End Get End Property End Class </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class B : A { public override int get_X(int y) { return base.$$get_X(y); } } </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestCrossLanguageNavigationToVBModuleMember() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class C { static void N() { A.$$M(); } } </Document> </Project> </Workspace> Test(workspace) End Sub #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestShowNotificationVB() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class SomeClass End Class C$$lass OtherClass Dim obj As SomeClass End Class </Document> </Project> </Workspace> Test(workspace, expectedResult:=False) End Sub <WorkItem(902119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902119")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionOnInferredFieldInitializer() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class2 Sub Test() Dim var1 = New With {Key .var2 = "Bob", Class2.va$$r3} End Sub Shared Property [|var3|]() As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WorkItem(885151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/885151")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestGoToDefinitionGlobalImportAlias() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <CompilationOptions> <GlobalImport>Goo = Importable.ImportMe</GlobalImport> </CompilationOptions> <Document> Public Class Class2 Sub Test() Dim x as Go$$o End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace Importable Public Class [|ImportMe|] End Class End Namespace </Document> </Project> </Workspace> Test(workspace) End Sub #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Exit() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit$$ Select End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSelect_Select() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M(parameter As String) Select Case parameter Case "a" Exit Select$$ End Select[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Exit Sub$$ End Sub[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M() As Integer Exit Sub$$ End Function[||] End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue$$ While End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]While True Continue While$$ End While End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitWhile_While() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() While True Exit While$$ End While[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_Continue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue$$ For Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For index As Integer = 1 To 5 Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitFor_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For index As Integer = 1 To 5 Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]For Each element In Nothing Continue For$$ Next End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitForEach_For() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() For Each element In Nothing Exit For$$ Next[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do While True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoWhileLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do While True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Until True Continue Do$$ Loop End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitDoUntilLoop_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Do Until True Exit Do$$ Loop[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopWhile_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop While True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnContinueDoLoopUntil_Do() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() [||]Do Continue Do$$ Loop Until True End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTry() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitTryInCatch() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Try Catch Exception Exit Try$$ End Try[||] End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Partial Sub M() End Sub [||]Partial Private Sub M() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSub_Partial_ReverseOrder() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Partial Private Sub M() Return$$ End Sub Partial Sub M() End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSubLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Sub() Return$$ End Sub End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Function M() As Int Return$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunction_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Function M([|x|] As Integer) As Integer Return x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Iterator Function M() As IEnumerable(Of Integer) Yield$$ 1 End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInIterator_OnValue() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Iterator Function M([|x|] As Integer) As IEnumerable(Of Integer) Yield x$$ End Function End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInFunctionLambda() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub M() Dim lambda = [||]Function() As Int Return$$ 1 End Function End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInConstructor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Sub New() Return$$ End Sub End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInOperator() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C [||]Public Shared Operator +(ByVal i As Integer) As Integer Return$$ 1 End Operator End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Return$$ 1 End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Set Return$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInGetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C ReadOnly Property P() As Integer [||]Get Exit Property$$ End Get End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnExitPropertyInSetAccessor() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property P() As Integer [||]Set Exit Property$$ End Set End Property End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInAddHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]AddHandler(ByVal value As EventHandler) Return$$ End AddHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRemoveHandler() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RemoveHandler(ByVal value As EventHandler) Return$$ End RemoveHandler End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Sub TestVisualBasicGoToOnReturnInRaiseEvent() Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Public Custom Event Click As EventHandler [||]RaiseEvent(ByVal sender As Object, ByVal e As EventArgs) Return$$ End RaiseEvent End Event End Class </Document> </Project> </Workspace> Test(workspace) End Sub End Class End Namespace
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Tools/AnalyzerRunner/AnalyzerRunnerHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { public static class AnalyzerRunnerHelper { static AnalyzerRunnerHelper() { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); #if NETCOREAPP // Since we do not inherit msbuild.deps.json when referencing the SDK copy // of MSBuild and because the SDK no longer ships with version matched assemblies, we // register an assembly loader that will load assemblies from the msbuild path with // equal or higher version numbers than requested. LooseVersionAssemblyLoader.Register(msBuildInstance.MSBuildPath); #endif MSBuildLocator.RegisterInstance(msBuildInstance); } public static MSBuildWorkspace CreateWorkspace() { var properties = new Dictionary<string, string> { #if NETCOREAPP // This property ensures that XAML files will be compiled in the current AppDomain // rather than a separate one. Any tasks isolated in AppDomains or tasks that create // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16. { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }, #endif // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "latest" }, }; return MSBuildWorkspace.Create(properties, AnalyzerRunnerMefHostServices.DefaultServices); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.MSBuild; namespace AnalyzerRunner { public static class AnalyzerRunnerHelper { static AnalyzerRunnerHelper() { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); #if NETCOREAPP // Since we do not inherit msbuild.deps.json when referencing the SDK copy // of MSBuild and because the SDK no longer ships with version matched assemblies, we // register an assembly loader that will load assemblies from the msbuild path with // equal or higher version numbers than requested. LooseVersionAssemblyLoader.Register(msBuildInstance.MSBuildPath); #endif MSBuildLocator.RegisterInstance(msBuildInstance); } public static MSBuildWorkspace CreateWorkspace() { var properties = new Dictionary<string, string> { #if NETCOREAPP // This property ensures that XAML files will be compiled in the current AppDomain // rather than a separate one. Any tasks isolated in AppDomains or tasks that create // AppDomains will likely not work due to https://github.com/Microsoft/MSBuildLocator/issues/16. { "AlwaysCompileMarkupFilesInSeparateDomain", bool.FalseString }, #endif // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "latest" }, }; return MSBuildWorkspace.Create(properties, AnalyzerRunnerMefHostServices.DefaultServices); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/CSharpTest2/Recommendations/DynamicKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DynamicKeywordRecommenderTests : RecommenderTests { private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender(); public DynamicKeywordRecommenderTests() { this.keywordText = "dynamic"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreProcessor() { await VerifyAbsenceAsync( @"class Program { #region $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class DynamicKeywordRecommenderTests : RecommenderTests { private readonly DynamicKeywordRecommender _recommender = new DynamicKeywordRecommender(); public DynamicKeywordRecommenderTests() { this.keywordText = "dynamic"; this.RecommendKeywordsAsync = (position, context) => Task.FromResult(_recommender.RecommendKeywords(position, context, CancellationToken.None)); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInFixedStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"fixed ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefExpression() { await VerifyAbsenceAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEnumBaseTypes() { await VerifyAbsenceAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(545303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545303")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreProcessor() { await VerifyAbsenceAsync( @"class Program { #region $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./eng/common/templates/job/source-build.yml
parameters: # This template adds arcade-powered source-build to CI. The template produces a server job with a # default ID 'Source_Build_Complete' to put in a dependency list if necessary. # Specifies the prefix for source-build jobs added to pipeline. Use this if disambiguation needed. jobNamePrefix: 'Source_Build' # Defines the platform on which to run the job. By default, a linux-x64 machine, suitable for # managed-only repositories. This is an object with these properties: # # name: '' # The name of the job. This is included in the job ID. # targetRID: '' # The name of the target RID to use, instead of the one auto-detected by Arcade. # nonPortable: false # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than # linux-x64), and compiling against distro-provided packages rather than portable ones. # skipPublishValidation: false # Disables publishing validation. By default, a check is performed to ensure no packages are # published by source-build. # container: '' # A container to use. Runs in docker. # pool: {} # A pool to use. Runs directly on an agent. # buildScript: '' # Specifies the build script to invoke to perform the build in the repo. The default # './build.sh' should work for typical Arcade repositories, but this is customizable for # difficult situations. # jobProperties: {} # A list of job properties to inject at the top level, for potential extensibility beyond # container and pool. platform: {} # The default VM host AzDO pool. This should be capable of running Docker containers: almost all # source-build builds run in Docker, including the default managed platform. defaultContainerHostPool: vmImage: ubuntu-20.04 jobs: - job: ${{ parameters.jobNamePrefix }}_${{ parameters.platform.name }} displayName: Source-Build (${{ parameters.platform.name }}) ${{ each property in parameters.platform.jobProperties }}: ${{ property.key }}: ${{ property.value }} ${{ if ne(parameters.platform.container, '') }}: container: ${{ parameters.platform.container }} ${{ if eq(parameters.platform.pool, '') }}: pool: ${{ parameters.defaultContainerHostPool }} ${{ if ne(parameters.platform.pool, '') }}: pool: ${{ parameters.platform.pool }} workspace: clean: all steps: - template: /eng/common/templates/steps/source-build.yml parameters: platform: ${{ parameters.platform }}
parameters: # This template adds arcade-powered source-build to CI. The template produces a server job with a # default ID 'Source_Build_Complete' to put in a dependency list if necessary. # Specifies the prefix for source-build jobs added to pipeline. Use this if disambiguation needed. jobNamePrefix: 'Source_Build' # Defines the platform on which to run the job. By default, a linux-x64 machine, suitable for # managed-only repositories. This is an object with these properties: # # name: '' # The name of the job. This is included in the job ID. # targetRID: '' # The name of the target RID to use, instead of the one auto-detected by Arcade. # nonPortable: false # Enables non-portable mode. This means a more specific RID (e.g. fedora.32-x64 rather than # linux-x64), and compiling against distro-provided packages rather than portable ones. # skipPublishValidation: false # Disables publishing validation. By default, a check is performed to ensure no packages are # published by source-build. # container: '' # A container to use. Runs in docker. # pool: {} # A pool to use. Runs directly on an agent. # buildScript: '' # Specifies the build script to invoke to perform the build in the repo. The default # './build.sh' should work for typical Arcade repositories, but this is customizable for # difficult situations. # jobProperties: {} # A list of job properties to inject at the top level, for potential extensibility beyond # container and pool. platform: {} # The default VM host AzDO pool. This should be capable of running Docker containers: almost all # source-build builds run in Docker, including the default managed platform. defaultContainerHostPool: vmImage: ubuntu-20.04 jobs: - job: ${{ parameters.jobNamePrefix }}_${{ parameters.platform.name }} displayName: Source-Build (${{ parameters.platform.name }}) ${{ each property in parameters.platform.jobProperties }}: ${{ property.key }}: ${{ property.value }} ${{ if ne(parameters.platform.container, '') }}: container: ${{ parameters.platform.container }} ${{ if eq(parameters.platform.pool, '') }}: pool: ${{ parameters.defaultContainerHostPool }} ${{ if ne(parameters.platform.pool, '') }}: pool: ${{ parameters.platform.pool }} workspace: clean: all steps: - template: /eng/common/templates/steps/source-build.yml parameters: platform: ${{ parameters.platform }}
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/Core/Portable/Shared/Extensions/INamespaceSymbolExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamespaceSymbolExtensions { private static readonly ConditionalWeakTable<INamespaceSymbol, List<string>> s_namespaceToNameMap = new(); public static readonly Comparison<INamespaceSymbol> CompareNamespaces = CompareTo; public static readonly IEqualityComparer<INamespaceSymbol> EqualityComparer = new Comparer(); private static List<string> GetNameParts(INamespaceSymbol? namespaceSymbol) { var result = new List<string>(); GetNameParts(namespaceSymbol, result); return result; } private static void GetNameParts(INamespaceSymbol? namespaceSymbol, List<string> result) { if (namespaceSymbol == null || namespaceSymbol.IsGlobalNamespace) { return; } GetNameParts(namespaceSymbol.ContainingNamespace, result); result.Add(namespaceSymbol.Name); } public static int CompareTo(this INamespaceSymbol n1, INamespaceSymbol n2) { var names1 = s_namespaceToNameMap.GetValue(n1, GetNameParts); var names2 = s_namespaceToNameMap.GetValue(n2, GetNameParts); for (var i = 0; i < Math.Min(names1.Count, names2.Count); i++) { var comp = names1[i].CompareTo(names2[i]); if (comp != 0) { return comp; } } return names1.Count - names2.Count; } public static IEnumerable<INamespaceOrTypeSymbol> GetAllNamespacesAndTypes( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceOrTypeSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetMembers().AsEnumerable()); yield return childNamespace; } else { var child = (INamedTypeSymbol)current; stack.Push(child.GetTypeMembers()); yield return child; } } } public static IEnumerable<INamespaceSymbol> GetAllNamespaces( this INamespaceSymbol namespaceSymbol, CancellationToken cancellationToken) { var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); if (current is INamespaceSymbol childNamespace) { stack.Push(childNamespace.GetNamespaceMembers()); yield return childNamespace; } } } public static IEnumerable<INamedTypeSymbol> GetAllTypes( this IEnumerable<INamespaceSymbol> namespaceSymbols, CancellationToken cancellationToken) { return namespaceSymbols.SelectMany(n => n.GetAllTypes(cancellationToken)); } /// <summary> /// Searches the namespace for namespaces with the provided name. /// </summary> public static IEnumerable<INamespaceSymbol> FindNamespaces( this INamespaceSymbol namespaceSymbol, string namespaceName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var stack = new Stack<INamespaceSymbol>(); stack.Push(namespaceSymbol); while (stack.Count > 0) { cancellationToken.ThrowIfCancellationRequested(); var current = stack.Pop(); var matchingChildren = current.GetMembers(namespaceName).OfType<INamespaceSymbol>(); foreach (var child in matchingChildren) { yield return child; } stack.Push(current.GetNamespaceMembers()); } } public static bool ContainsAccessibleTypesOrNamespaces( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly) { using var namespaceQueue = SharedPools.Default<Queue<INamespaceOrTypeSymbol>>().GetPooledObject(); return ContainsAccessibleTypesOrNamespacesWorker(namespaceSymbol, assembly, namespaceQueue.Object); } public static INamespaceSymbol? GetQualifiedNamespace( this INamespaceSymbol globalNamespace, string namespaceName) { var namespaceSymbol = globalNamespace; foreach (var name in namespaceName.Split('.')) { var members = namespaceSymbol.GetMembers(name); namespaceSymbol = members.Count() == 1 ? members.First() as INamespaceSymbol : null; if (namespaceSymbol is null) { break; } } return namespaceSymbol; } private static bool ContainsAccessibleTypesOrNamespacesWorker( this INamespaceSymbol namespaceSymbol, IAssemblySymbol assembly, Queue<INamespaceOrTypeSymbol> namespaceQueue) { // Note: we only store INamespaceSymbols in here, even though we type it as // INamespaceOrTypeSymbol. This is because when we call GetMembers below we // want it to return an ImmutableArray so we don't incur any costs to iterate // over it. foreach (var constituent in namespaceSymbol.ConstituentNamespaces) { // Assume that any namespace in our own assembly is accessible to us. This saves a // lot of cpu time checking namespaces. if (Equals(constituent.ContainingAssembly, assembly)) { return true; } namespaceQueue.Enqueue(constituent); } while (namespaceQueue.Count > 0) { var ns = namespaceQueue.Dequeue(); // Upcast so we call the 'GetMembers' method that returns an ImmutableArray. var members = ns.GetMembers(); foreach (var namespaceOrType in members) { if (namespaceOrType.Kind == SymbolKind.NamedType) { if (namespaceOrType.IsAccessibleWithin(assembly)) { return true; } } else { namespaceQueue.Enqueue((INamespaceSymbol)namespaceOrType); } } } return false; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PEGlobalNamespaceSymbol.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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Reflection.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Friend NotInheritable Class PEGlobalNamespaceSymbol Inherits PENamespaceSymbol ''' <summary> ''' The module containing the namespace. ''' </summary> ''' <remarks></remarks> Private ReadOnly _moduleSymbol As PEModuleSymbol Friend Sub New(moduleSymbol As PEModuleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _moduleSymbol = moduleSymbol End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _moduleSymbol End Get End Property Friend Overrides ReadOnly Property ContainingPEModule As PEModuleSymbol Get Return _moduleSymbol End Get End Property Public Overrides ReadOnly Property Name As String Get Return String.Empty End Get End Property Public Overrides ReadOnly Property IsGlobalNamespace As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _moduleSymbol.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _moduleSymbol End Get End Property Protected Overrides Sub EnsureAllMembersLoaded() If m_lazyTypes Is Nothing OrElse m_lazyMembers Is Nothing Then Dim groups As IEnumerable(Of IGrouping(Of String, TypeDefinitionHandle)) Try groups = _moduleSymbol.Module.GroupTypesByNamespaceOrThrow(IdentifierComparison.Comparer) Catch mrEx As BadImageFormatException groups = SpecializedCollections.EmptyEnumerable(Of IGrouping(Of String, TypeDefinitionHandle))() End Try LoadAllMembers(groups) End If End Sub ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Reflection.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Friend NotInheritable Class PEGlobalNamespaceSymbol Inherits PENamespaceSymbol ''' <summary> ''' The module containing the namespace. ''' </summary> ''' <remarks></remarks> Private ReadOnly _moduleSymbol As PEModuleSymbol Friend Sub New(moduleSymbol As PEModuleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _moduleSymbol = moduleSymbol End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _moduleSymbol End Get End Property Friend Overrides ReadOnly Property ContainingPEModule As PEModuleSymbol Get Return _moduleSymbol End Get End Property Public Overrides ReadOnly Property Name As String Get Return String.Empty End Get End Property Public Overrides ReadOnly Property IsGlobalNamespace As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _moduleSymbol.ContainingAssembly End Get End Property Public Overrides ReadOnly Property ContainingModule As ModuleSymbol Get Return _moduleSymbol End Get End Property Protected Overrides Sub EnsureAllMembersLoaded() If m_lazyTypes Is Nothing OrElse m_lazyMembers Is Nothing Then Dim groups As IEnumerable(Of IGrouping(Of String, TypeDefinitionHandle)) Try groups = _moduleSymbol.Module.GroupTypesByNamespaceOrThrow(IdentifierComparison.Comparer) Catch mrEx As BadImageFormatException groups = SpecializedCollections.EmptyEnumerable(Of IGrouping(Of String, TypeDefinitionHandle))() End Try LoadAllMembers(groups) End If End Sub ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Features/Core/Portable/Completion/Providers/AbstractOverrideCompletionProvider.ItemGetter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractOverrideCompletionProvider { private partial class ItemGetter { private readonly CancellationToken _cancellationToken; private readonly int _position; private readonly AbstractOverrideCompletionProvider _provider; private readonly SymbolDisplayFormat _overrideNameFormat = SymbolDisplayFormats.NameFormat.WithParameterOptions( SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut) .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); private readonly Document _document; private readonly SourceText _text; private readonly SyntaxTree _syntaxTree; private readonly int _startLineNumber; private ItemGetter( AbstractOverrideCompletionProvider overrideCompletionProvider, Document document, int position, SourceText text, SyntaxTree syntaxTree, int startLineNumber, CancellationToken cancellationToken) { _provider = overrideCompletionProvider; _document = document; _position = position; _text = text; _syntaxTree = syntaxTree; _startLineNumber = startLineNumber; _cancellationToken = cancellationToken; } public static async Task<ItemGetter> CreateAsync( AbstractOverrideCompletionProvider overrideCompletionProvider, Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var startLineNumber = text.Lines.IndexOf(position); return new ItemGetter(overrideCompletionProvider, document, position, text, syntaxTree, startLineNumber, cancellationToken); } public async Task<ImmutableArray<CompletionItem>> GetItemsAsync() { // modifiers* override modifiers* type? | if (!TryCheckForTrailingTokens(_position)) return default; var startToken = _provider.FindStartingToken(_syntaxTree, _position, _cancellationToken); if (startToken.Parent == null) return default; var semanticModel = await _document.ReuseExistingSpeculativeModelAsync(startToken.Parent, _cancellationToken).ConfigureAwait(false); if (!_provider.TryDetermineReturnType(startToken, semanticModel, _cancellationToken, out var returnType, out var tokenAfterReturnType) || !_provider.TryDetermineModifiers(tokenAfterReturnType, _text, _startLineNumber, out var seenAccessibility, out var modifiers) || !TryDetermineOverridableMembers(semanticModel, startToken, seenAccessibility, out var overridableMembers)) { return default; } return _provider.FilterOverrides(overridableMembers, returnType) .SelectAsArray(m => CreateItem(m, semanticModel, startToken, modifiers)); } private CompletionItem CreateItem( ISymbol symbol, SemanticModel semanticModel, SyntaxToken startToken, DeclarationModifiers modifiers) { var position = startToken.SpanStart; var displayString = symbol.ToMinimalDisplayString(semanticModel, position, _overrideNameFormat); return MemberInsertionCompletionItem.Create( displayString, displayTextSuffix: "", modifiers, _startLineNumber, symbol, startToken, position, rules: GetRules()); } private bool TryDetermineOverridableMembers( SemanticModel semanticModel, SyntaxToken startToken, Accessibility seenAccessibility, out ImmutableArray<ISymbol> overridableMembers) { var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, _cancellationToken); var result = containingType.GetOverridableMembers(_cancellationToken); // Filter based on accessibility if (seenAccessibility != Accessibility.NotApplicable) { result = result.WhereAsArray(m => m.DeclaredAccessibility == seenAccessibility); } overridableMembers = result; return overridableMembers.Length > 0; } private bool TryCheckForTrailingTokens(int position) { var root = _syntaxTree.GetRoot(_cancellationToken); var token = root.FindToken(position); // Don't want to offer Override completion if there's a token after the current // position. if (token.SpanStart > position) { return false; } // If the next token is also on our line then we don't want to offer completion. if (IsOnStartLine(token.GetNextToken().SpanStart)) { return false; } return true; } private bool IsOnStartLine(int position) => _text.Lines.IndexOf(position) == _startLineNumber; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractOverrideCompletionProvider { private partial class ItemGetter { private readonly CancellationToken _cancellationToken; private readonly int _position; private readonly AbstractOverrideCompletionProvider _provider; private readonly SymbolDisplayFormat _overrideNameFormat = SymbolDisplayFormats.NameFormat.WithParameterOptions( SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut) .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); private readonly Document _document; private readonly SourceText _text; private readonly SyntaxTree _syntaxTree; private readonly int _startLineNumber; private ItemGetter( AbstractOverrideCompletionProvider overrideCompletionProvider, Document document, int position, SourceText text, SyntaxTree syntaxTree, int startLineNumber, CancellationToken cancellationToken) { _provider = overrideCompletionProvider; _document = document; _position = position; _text = text; _syntaxTree = syntaxTree; _startLineNumber = startLineNumber; _cancellationToken = cancellationToken; } public static async Task<ItemGetter> CreateAsync( AbstractOverrideCompletionProvider overrideCompletionProvider, Document document, int position, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var startLineNumber = text.Lines.IndexOf(position); return new ItemGetter(overrideCompletionProvider, document, position, text, syntaxTree, startLineNumber, cancellationToken); } public async Task<ImmutableArray<CompletionItem>> GetItemsAsync() { // modifiers* override modifiers* type? | if (!TryCheckForTrailingTokens(_position)) return default; var startToken = _provider.FindStartingToken(_syntaxTree, _position, _cancellationToken); if (startToken.Parent == null) return default; var semanticModel = await _document.ReuseExistingSpeculativeModelAsync(startToken.Parent, _cancellationToken).ConfigureAwait(false); if (!_provider.TryDetermineReturnType(startToken, semanticModel, _cancellationToken, out var returnType, out var tokenAfterReturnType) || !_provider.TryDetermineModifiers(tokenAfterReturnType, _text, _startLineNumber, out var seenAccessibility, out var modifiers) || !TryDetermineOverridableMembers(semanticModel, startToken, seenAccessibility, out var overridableMembers)) { return default; } return _provider.FilterOverrides(overridableMembers, returnType) .SelectAsArray(m => CreateItem(m, semanticModel, startToken, modifiers)); } private CompletionItem CreateItem( ISymbol symbol, SemanticModel semanticModel, SyntaxToken startToken, DeclarationModifiers modifiers) { var position = startToken.SpanStart; var displayString = symbol.ToMinimalDisplayString(semanticModel, position, _overrideNameFormat); return MemberInsertionCompletionItem.Create( displayString, displayTextSuffix: "", modifiers, _startLineNumber, symbol, startToken, position, rules: GetRules()); } private bool TryDetermineOverridableMembers( SemanticModel semanticModel, SyntaxToken startToken, Accessibility seenAccessibility, out ImmutableArray<ISymbol> overridableMembers) { var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, _cancellationToken); var result = containingType.GetOverridableMembers(_cancellationToken); // Filter based on accessibility if (seenAccessibility != Accessibility.NotApplicable) { result = result.WhereAsArray(m => m.DeclaredAccessibility == seenAccessibility); } overridableMembers = result; return overridableMembers.Length > 0; } private bool TryCheckForTrailingTokens(int position) { var root = _syntaxTree.GetRoot(_cancellationToken); var token = root.FindToken(position); // Don't want to offer Override completion if there's a token after the current // position. if (token.SpanStart > position) { return false; } // If the next token is also on our line then we don't want to offer completion. if (IsOnStartLine(token.GetNextToken().SpanStart)) { return false; } return true; } private bool IsOnStartLine(int position) => _text.Lines.IndexOf(position) == _startLineNumber; } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxNodeOrToken.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal struct EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> { public readonly TSyntaxNode? Node; public readonly EmbeddedSyntaxToken<TSyntaxKind> Token; private EmbeddedSyntaxNodeOrToken(TSyntaxNode node) : this() { RoslynDebug.AssertNotNull(node); Node = node; } private EmbeddedSyntaxNodeOrToken(EmbeddedSyntaxToken<TSyntaxKind> token) : this() { Debug.Assert((int)(object)token.Kind != 0); Token = token; } [MemberNotNullWhen(true, nameof(Node))] public bool IsNode => Node != null; public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(TSyntaxNode node) => new(node); public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(EmbeddedSyntaxToken<TSyntaxKind> token) => new(token); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal struct EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode> where TSyntaxKind : struct where TSyntaxNode : EmbeddedSyntaxNode<TSyntaxKind, TSyntaxNode> { public readonly TSyntaxNode? Node; public readonly EmbeddedSyntaxToken<TSyntaxKind> Token; private EmbeddedSyntaxNodeOrToken(TSyntaxNode node) : this() { RoslynDebug.AssertNotNull(node); Node = node; } private EmbeddedSyntaxNodeOrToken(EmbeddedSyntaxToken<TSyntaxKind> token) : this() { Debug.Assert((int)(object)token.Kind != 0); Token = token; } [MemberNotNullWhen(true, nameof(Node))] public bool IsNode => Node != null; public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(TSyntaxNode node) => new(node); public static implicit operator EmbeddedSyntaxNodeOrToken<TSyntaxKind, TSyntaxNode>(EmbeddedSyntaxToken<TSyntaxKind> token) => new(token); } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ISwitchOperation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ISwitchOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_01() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_02() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: var x = 3; input = x; break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Locals: Local_1: System.Int32 x Sections: ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input = x') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_03() { string source = @" using System; class Program { static void M(object input) { /*<bind>*/switch (input) { case int x: case long y: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Sections: ISwitchCaseOperation (2 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;') Locals: Local_1: System.Int32 x Local_2: System.Int64 y Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case long y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'long y') (InputType: System.Object, NarrowedType: System.Int64, DeclaredSymbol: System.Int64 y, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_04() { string source = @" using System; class Program { static void M(object input) { /*<bind>*/switch (input) { case int y: var x = 3; input = x + y; break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Locals: Local_1: System.Int32 x Sections: ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int y: ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) Body: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x + y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'input = x + y') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x + y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LabelsInSwitch_01() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: goto case 2; case 2: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... oto case 2;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto case 2;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 2: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 2) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 2:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LabelsInSwitch_02() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: goto default; default: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... to default;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto default;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'default: ... break;') Clauses: IDefaultCaseClauseOperation (Label Id: 2) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_01() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_02() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: result = true; break; case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_03() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: result = false; break; default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_04() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_05() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 0: bool x = true; result = x; break; case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Boolean x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'x = true') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x = true') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B6] Leaving: {R2} {R1} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} {R1} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B3] [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_06() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_07() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: default: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_08() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 2: default: case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_09() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: goto case 3; case 2: goto default; case 3: result = true; break; default: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '3') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B1] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R1} Block[B5] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_10() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: goto case 3; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(9,17): error CS0159: No such label 'case 3:' within the scope of the goto statement // goto case 3; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto case 3;").WithArguments("case 3:").WithLocation(9, 17), // file.cs(8,13): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (2) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto case 3;') Children(0) Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_11() { string source = @" public sealed class MyClass { void M(bool result, long input) /*<bind>*/{ switch (input) { default: result = false; break; case 1: result = result; break; default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(14,13): error CS0152: The switch statement contains multiple cases with the label value 'default' // default: Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(14, 13), // file.cs(12,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // result = result; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "result = result").WithLocation(12, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = result;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = result') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B2] [B3] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_12() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1L: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // case 1L: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1L') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1, IsInvalid) (Syntax: '1L') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_13() { string source = @" public sealed class MyClass { void M(bool result, MyClass input, MyClass other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ public static bool operator ==(MyClass x, MyClass y) => false; public static bool operator !=(MyClass x, MyClass y) => true; public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: MyClass, NarrowedType: MyClass) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_14() { string source = @" public sealed class MyClass { void M(bool result, MyClass input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ public static bool operator ==(MyClass x, long y) => false; public static bool operator !=(MyClass x, long y) => true; public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0029: Cannot implicitly convert type 'int' to 'MyClass' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "MyClass").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_15() { string source = @" public sealed class MyClass { void M(bool result, MyClass input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ public static implicit operator MyClass(long x) => null; } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1: Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: MyClass MyClass.op_Implicit(System.Int64 x)) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: MyClass MyClass.op_Implicit(System.Int64 x)) (ImplicitUserDefined) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_16() { string source = @" public sealed class MyClass { void M(bool result) /*<bind>*/{ case 1: result = false; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(5,16): error CS1513: } expected // /*<bind>*/{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 16), // file.cs(6,19): error CS1002: ; expected // case 1: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 19), // file.cs(6,19): error CS1513: } expected // case 1: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 19), // file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '1') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_17() { string source = @" public sealed class MyClass { void M(bool result) /*<bind>*/{ default: result = false; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(6,13): error CS8716: There is no target type for the default literal. // default: Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 13), // file.cs(6,20): error CS1002: ; expected // default: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 20), // file.cs(6,20): error CS1513: } expected // default: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 20), // file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'default') Expression: IDefaultValueOperation (OperationKind.DefaultValue, Type: ?, IsInvalid) (Syntax: 'default') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_18() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_19() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case null: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'null') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_20() { string source = @" public sealed class MyClass { void M(bool result, int? input, int? other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_21() { string source = @" public sealed class MyClass { void M(bool result, int input, int? other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) // case other: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "other").WithArguments("int?", "int").WithLocation(8, 18), // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitNullable) Operand: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_22() { string source = @" public sealed class MyClass { void M(bool result, dynamic input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchIOperation_022() { string source = @" public sealed class MyClass { void M(bool result, dynamic input) { /*<bind>*/switch (input) { case 1: result = false; break; }/*</bind>*/ } } "; var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 2 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_23() { string source = @" public sealed class MyClass { void M(bool result, dynamic input, dynamic other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: dynamic, NarrowedType: dynamic) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_24() { string source = @" public sealed class MyClass { void M(bool result, int? input1, int input2) /*<bind>*/{ switch (input1 ?? input2) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input1') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Arguments(0) Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1 ?? input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_25() { string source = @" public sealed class MyClass { void M(bool result, int? input1, int input2, int input3) /*<bind>*/{ switch (input3) { case input1 ?? input2: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case input1 ?? input2: Diagnostic(ErrorCode.ERR_ConstantExpected, "input1 ?? input2").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input3') Value: IParameterReferenceOperation: input3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input3') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1') Arguments(0) Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input3') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_26() { string source = @" public sealed class MyClass { void M(int input1, MyClass input2) /*<bind>*/{ switch (input1) { case 1: input2?.ToString(); break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} 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: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input2') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2') Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2') Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_27() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_28() { string source = @" public sealed class MyClass { void M(bool result, object input, int? other) /*<bind>*/{ switch (input) { case other ?? 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other ?? 1: Diagnostic(ErrorCode.ERR_ConstantExpected, "other ?? 1").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other') Arguments(0) Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_29() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case int x: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Int32 x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_30() { string source = @" public sealed class MyClass { void M(bool result, object input1, bool other2, bool other3, bool other4) /*<bind>*/{ switch (input1) { case int x when (other2 ? other3 : other4) : result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Int32 x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: other2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: other3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other3') Leaving: {R2} {R1} Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: other4 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other4') Leaving: {R2} {R1} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} {R1} } } Block[B7] - Exit Predecessors: [B2] [B4] [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_31() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1: result = false; break; case 2: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '2') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Leaving: {R1} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B2] [B3] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_32() { string source = @" public sealed class MyClass { void M(bool result, object input, bool? guard) /*<bind>*/{ switch (input) { case 1 when guard ?? throw null: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} 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: 'guard') Value: IParameterReferenceOperation: guard (OperationKind.ParameterReference, Type: System.Boolean?) (Syntax: 'guard') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'guard') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( System.Boolean System.Boolean?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'guard') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard') Arguments(0) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B1] [B3] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_33() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1 when guard: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,25): error CS0103: The name 'guard' does not exist in the current context // case 1 when guard: Diagnostic(ErrorCode.ERR_NameNotInContext, "guard").WithArguments("guard").WithLocation(8, 25) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'guard') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'guard') Children(0) Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_34() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1+TakeOutParam(3, out MyClass x1): result = false; break; } }/*</bind>*/ int TakeOutParam(int a, out MyClass b) { b = default; return a; } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1+TakeOutParam(3, out MyClass x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "1+TakeOutParam(3, out MyClass x1)").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [MyClass x1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+TakeOutPa ... MyClass x1)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+TakeOutPa ... MyClass x1)') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Right: IInvocationOperation ( System.Int32 MyClass.TakeOutParam(System.Int32 a, out MyClass b)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... MyClass x1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'TakeOutParam') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out MyClass x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: MyClass, IsInvalid) (Syntax: 'MyClass x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: MyClass, IsInvalid) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_35() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case 1+(input is int x1 ? x1 : 0): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1+(input is int x1 ? x1 : 0): Diagnostic(ErrorCode.ERR_ConstantExpected, "1+(input is int x1 ? x1 : 0)").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { Locals: [System.Int32 x1] .locals {R3} { CaptureIds: [1] [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'input is int x1') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x1') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x1, MatchesNull: False) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1') Value: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+(input is ... 1 ? x1 : 0)') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input is int x1 ? x1 : 0') Leaving: {R3} {R2} {R1} Next (Regular) Block[B6] Leaving: {R3} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} {R1} } } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns, CompilerFeature.Dataflow)] [Fact] public void EmptySwitchExpressionFlow() { string source = @" class Program { public static void Main() /*<bind>*/{ var r = 1 switch { }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(6,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 19), // file.cs(6,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 19) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [? r] CaptureIds: [0] .locals {R2} { CaptureIds: [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: '1 switch { }') Arguments(0) Initializer: null Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }') Left: ILocalReferenceOperation: r (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: '1 switch { }') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_36() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case < 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[0]; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< 1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< 1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_37() { string source = @" public sealed class MyClass { void M(bool result, int input, int other) /*<bind>*/{ switch (input) { case < other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0150: A constant value is expected // case < other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 20) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '< other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null, IsInvalid) (Syntax: '< other') (InputType: System.Int32, NarrowedType: System.Int32) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_38() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case < (true ? 10 : 11): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B5] Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< (true ? 10 : 11)') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_39() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case not < (true ? 10 : 11): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B5] Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'not < (true ? 10 : 11)') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not < (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_40() { string source = @" public sealed class MyClass { bool M(char input) /*<bind>*/{ switch (input) { case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or '_': return true; } return false; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '(>= 'A' and ... 'z') or '_'') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... 'z') or '_'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') RightPattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R1} } Block[B3] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_41() { string source = @" public sealed class MyClass { bool M(object input) /*<bind>*/{ switch (input) { case int or long or ulong: return true; default: return false; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int or long or ulong') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or ulong') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'ulong') (InputType: System.Object, NarrowedType: System.UInt64, MatchedType: System.UInt64) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ISwitchOperation : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_01() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_02() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: var x = 3; input = x; break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Locals: Local_1: System.Int32 x Sections: ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'input = x') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_03() { string source = @" using System; class Program { static void M(object input) { /*<bind>*/switch (input) { case int x: case long y: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Sections: ISwitchCaseOperation (2 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int x: ... break;') Locals: Local_1: System.Int32 x Local_2: System.Int64 y Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int x:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) IPatternCaseClauseOperation (Label Id: 2) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case long y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'long y') (InputType: System.Object, NarrowedType: System.Int64, DeclaredSymbol: System.Int64 y, MatchesNull: False) Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LocalsInSwitch_04() { string source = @" using System; class Program { static void M(object input) { /*<bind>*/switch (input) { case int y: var x = 3; input = x + y; break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Locals: Local_1: System.Int32 x Sections: ISwitchCaseOperation (1 case clauses, 3 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case int y: ... break;') Locals: Local_1: System.Int32 y Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case int y:') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int y') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 y, MatchesNull: False) Body: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var x = 3;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var x = 3') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = 3') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input = x + y;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Object) (Syntax: 'input = x + y') Left: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x + y') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LabelsInSwitch_01() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: goto case 2; case 2: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... oto case 2;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto case 2;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 2: ... break;') Clauses: ISingleValueCaseClauseOperation (Label Id: 2) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 2:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void LabelsInSwitch_02() { string source = @" using System; class Program { static void M(int input) { /*<bind>*/switch (input) { case 1: goto default; default: break; }/*</bind>*/ } } "; string expectedOperationTree = @" ISwitchOperation (2 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... to default;') Clauses: ISingleValueCaseClauseOperation (Label Id: 1) (CaseKind.SingleValue) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBranchOperation (BranchKind.GoTo, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'goto default;') ISwitchCaseOperation (1 case clauses, 1 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'default: ... break;') Clauses: IDefaultCaseClauseOperation (Label Id: 2) (CaseKind.Default) (OperationKind.CaseClause, Type: null) (Syntax: 'default:') Body: IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_01() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_02() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: result = true; break; case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_03() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: result = false; break; default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_04() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_05() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 0: bool x = true; result = x; break; case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Boolean x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '0') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsImplicit) (Syntax: 'x = true') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean, IsImplicit) (Syntax: 'x = true') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = x;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = x') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B6] Leaving: {R2} {R1} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} {R1} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R2} {R1} } } Block[B6] - Exit Predecessors: [B3] [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_06() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { default: case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_07() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: default: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_08() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 2: default: case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B1] [B2*2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_09() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: goto case 3; case 2: goto default; case 3: result = true; break; default: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B4] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B5] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '3') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B1] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B6] Leaving: {R1} Block[B5] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_10() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1: goto case 3; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(9,17): error CS0159: No such label 'case 3:' within the scope of the goto statement // goto case 3; Diagnostic(ErrorCode.ERR_LabelNotFound, "goto case 3;").WithArguments("case 3:").WithLocation(9, 17), // file.cs(8,13): error CS8070: Control cannot fall out of switch from final case label ('case 1:') // case 1: Diagnostic(ErrorCode.ERR_SwitchFallOut, "case 1:").WithArguments("case 1:").WithLocation(8, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (2) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'goto case 3;') Children(0) Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_11() { string source = @" public sealed class MyClass { void M(bool result, long input) /*<bind>*/{ switch (input) { default: result = false; break; case 1: result = result; break; default: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(14,13): error CS0152: The switch statement contains multiple cases with the label value 'default' // default: Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(14, 13), // file.cs(12,17): warning CS1717: Assignment made to same variable; did you mean to assign something else? // result = result; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "result = result").WithLocation(12, 17) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int64) (Syntax: 'input') Jump if False (Regular) to Block[B2] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int64, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = result;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = result') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block [UnReachable] Predecessors (0) Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B2] [B3] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_12() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1L: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0266: Cannot implicitly convert type 'long' to 'int'. An explicit conversion exists (are you missing a cast?) // case 1L: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1L").WithArguments("long", "int").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1L') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1L') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int64, Constant: 1, IsInvalid) (Syntax: '1L') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_13() { string source = @" public sealed class MyClass { void M(bool result, MyClass input, MyClass other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ public static bool operator ==(MyClass x, MyClass y) => false; public static bool operator !=(MyClass x, MyClass y) => true; public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: MyClass, NarrowedType: MyClass) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: MyClass, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_14() { string source = @" public sealed class MyClass { void M(bool result, MyClass input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ public static bool operator ==(MyClass x, long y) => false; public static bool operator !=(MyClass x, long y) => true; public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0029: Cannot implicitly convert type 'int' to 'MyClass' // case 1: Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "MyClass").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_15() { string source = @" public sealed class MyClass { void M(bool result, MyClass input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ public static implicit operator MyClass(long x) => null; } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1: Diagnostic(ErrorCode.ERR_ConstantExpected, "1").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: '1') (InputType: MyClass, NarrowedType: MyClass) Value: IConversionOperation (TryCast: False, Unchecked) (OperatorMethod: MyClass MyClass.op_Implicit(System.Int64 x)) (OperationKind.Conversion, Type: MyClass, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: True) (MethodSymbol: MyClass MyClass.op_Implicit(System.Int64 x)) (ImplicitUserDefined) Operand: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int64, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNumeric) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_16() { string source = @" public sealed class MyClass { void M(bool result) /*<bind>*/{ case 1: result = false; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(5,16): error CS1513: } expected // /*<bind>*/{ Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 16), // file.cs(6,19): error CS1002: ; expected // case 1: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 19), // file.cs(6,19): error CS1513: } expected // case 1: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 19), // file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '1') Expression: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_17() { string source = @" public sealed class MyClass { void M(bool result) /*<bind>*/{ default: result = false; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(6,13): error CS8716: There is no target type for the default literal. // default: Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 13), // file.cs(6,20): error CS1002: ; expected // default: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(6, 20), // file.cs(6,20): error CS1513: } expected // default: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(6, 20), // file.cs(10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'default') Expression: IDefaultValueOperation (OperationKind.DefaultValue, Type: ?, IsInvalid) (Syntax: 'default') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_18() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_19() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case null: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: 'null') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NullLiteral) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_20() { string source = @" public sealed class MyClass { void M(bool result, int? input, int? other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_21() { string source = @" public sealed class MyClass { void M(bool result, int input, int? other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) // case other: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "other").WithArguments("int?", "int").WithLocation(8, 18), // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ExplicitNullable) Operand: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_22() { string source = @" public sealed class MyClass { void M(bool result, dynamic input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchIOperation_022() { string source = @" public sealed class MyClass { void M(bool result, dynamic input) { /*<bind>*/switch (input) { case 1: result = false; break; }/*</bind>*/ } } "; var expectedDiagnostics = DiagnosticDescription.None; var expectedOperationTree = @" ISwitchOperation (1 cases, Exit Label Id: 0) (OperationKind.Switch, Type: null) (Syntax: 'switch (inp ... }') Switch expression: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Sections: ISwitchCaseOperation (1 case clauses, 2 statements) (OperationKind.SwitchCase, Type: null) (Syntax: 'case 1: ... break;') Clauses: IPatternCaseClauseOperation (Label Id: 1) (CaseKind.Pattern) (OperationKind.CaseClause, Type: null) (Syntax: 'case 1:') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: dynamic, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') IBranchOperation (BranchKind.Break, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeAndDiagnosticsForTest<SwitchStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_23() { string source = @" public sealed class MyClass { void M(bool result, dynamic input, dynamic other) /*<bind>*/{ switch (input) { case other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') (InputType: dynamic, NarrowedType: dynamic) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_24() { string source = @" public sealed class MyClass { void M(bool result, int? input1, int input2) /*<bind>*/{ switch (input1 ?? input2) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'input1') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input1') Arguments(0) Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1 ?? input2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B4] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_25() { string source = @" public sealed class MyClass { void M(bool result, int? input1, int input2, int input3) /*<bind>*/{ switch (input3) { case input1 ?? input2: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case input1 ?? input2: Diagnostic(ErrorCode.ERR_ConstantExpected, "input1 ?? input2").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input3') Value: IParameterReferenceOperation: input3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input3') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'input1') Arguments(0) Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input3') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input1 ?? input2') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_26() { string source = @" public sealed class MyClass { void M(int input1, MyClass input2) /*<bind>*/{ switch (input1) { case 1: input2?.ToString(); break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsImplicit) (Syntax: '1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} 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: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'input2') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'input2') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2') Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'input2?.ToString();') Expression: IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: '.ToString()') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'input2') Arguments(0) Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_27() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_28() { string source = @" public sealed class MyClass { void M(bool result, object input, int? other) /*<bind>*/{ switch (input) { case other ?? 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,18): error CS0150: A constant value is expected // case other ?? 1: Diagnostic(ErrorCode.ERR_ConstantExpected, "other ?? 1").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { CaptureIds: [2] .locals {R3} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'other') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other') Leaving: {R3} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'other') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'other') Arguments(0) Next (Regular) Block[B5] Leaving: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') (InputType: System.Object, NarrowedType: System.Object) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (Boxing) Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'other ?? 1') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_29() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case int x: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Int32 x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_30() { string source = @" public sealed class MyClass { void M(bool result, object input1, bool other2, bool other3, bool other4) /*<bind>*/{ switch (input1) { case int x when (other2 ? other3 : other4) : result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [System.Int32 x] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int x') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input1') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int x') (InputType: System.Object, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x, MatchesNull: False) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: other2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: other3 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other3') Leaving: {R2} {R1} Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: other4 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'other4') Leaving: {R2} {R1} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} {R1} } } Block[B7] - Exit Predecessors: [B2] [B4] [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_31() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1: result = false; break; case 2: result = true; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '2') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsImplicit) (Syntax: '2') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Leaving: {R1} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = true;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = true') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B2] [B3] [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_32() { string source = @" public sealed class MyClass { void M(bool result, object input, bool? guard) /*<bind>*/{ switch (input) { case 1 when guard ?? throw null: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} 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: 'guard') Value: IParameterReferenceOperation: guard (OperationKind.ParameterReference, Type: System.Boolean?) (Syntax: 'guard') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'guard') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IInvocationOperation ( System.Boolean System.Boolean?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Boolean, IsImplicit) (Syntax: 'guard') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean?, IsImplicit) (Syntax: 'guard') Arguments(0) Leaving: {R2} {R1} Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Exception, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) (ImplicitReference) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B1] [B3] [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_33() { string source = @" public sealed class MyClass { void M(bool result, object input) /*<bind>*/{ switch (input) { case 1 when guard: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(8,25): error CS0103: The name 'guard' does not exist in the current context // case 1 when guard: Diagnostic(ErrorCode.ERR_NameNotInContext, "guard").WithArguments("guard").WithLocation(8, 25) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Object, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'guard') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'guard') Children(0) Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit Predecessors: [B1] [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_34() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case 1+TakeOutParam(3, out MyClass x1): result = false; break; } }/*</bind>*/ int TakeOutParam(int a, out MyClass b) { b = default; return a; } } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1+TakeOutParam(3, out MyClass x1): Diagnostic(ErrorCode.ERR_ConstantExpected, "1+TakeOutParam(3, out MyClass x1)").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { Locals: [MyClass x1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+TakeOutPa ... MyClass x1)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+TakeOutPa ... MyClass x1)') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Right: IInvocationOperation ( System.Int32 MyClass.TakeOutParam(System.Int32 a, out MyClass b)) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'TakeOutPara ... MyClass x1)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: MyClass, IsInvalid, IsImplicit) (Syntax: 'TakeOutParam') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '3') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: b) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'out MyClass x1') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: MyClass, IsInvalid) (Syntax: 'MyClass x1') ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: MyClass, IsInvalid) (Syntax: 'x1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B4] Leaving: {R2} {R1} } } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchFlow_35() { string source = @" public sealed class MyClass { void M(bool result, int? input) /*<bind>*/{ switch (input) { case 1+(input is int x1 ? x1 : 0): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,18): error CS0150: A constant value is expected // case 1+(input is int x1 ? x1 : 0): Diagnostic(ErrorCode.ERR_ConstantExpected, "1+(input is int x1 ? x1 : 0)").WithLocation(8, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} {R3} .locals {R2} { Locals: [System.Int32 x1] .locals {R3} { CaptureIds: [1] [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'input is int x1') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32?, IsInvalid) (Syntax: 'input') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int x1') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 x1, MatchesNull: False) Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'x1') Value: ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '0') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0, IsInvalid) (Syntax: '0') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IBinaryOperation (BinaryOperatorKind.Equals, IsLifted) (OperationKind.Binary, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'input') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '1+(input is ... 1 ? x1 : 0)') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (ImplicitNullable) Operand: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, IsInvalid) (Syntax: '1+(input is ... 1 ? x1 : 0)') Left: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1') Right: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'input is int x1 ? x1 : 0') Leaving: {R3} {R2} {R1} Next (Regular) Block[B6] Leaving: {R3} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} {R1} } } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns, CompilerFeature.Dataflow)] [Fact] public void EmptySwitchExpressionFlow() { string source = @" class Program { public static void Main() /*<bind>*/{ var r = 1 switch { }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(6,19): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // var r = 1 switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 19), // file.cs(6,19): error CS8506: No best type was found for the switch expression. // var r = 1 switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 19) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [? r] CaptureIds: [0] .locals {R2} { CaptureIds: [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B2] Leaving: {R2} } Block[B2] - Block Predecessors: [B1] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: '1 switch { }') Arguments(0) Initializer: null Block[B3] - Block [UnReachable] Predecessors (0) Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }') Left: ILocalReferenceOperation: r (IsDeclaration: True) (OperationKind.LocalReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'r = 1 switch { }') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: '1 switch { }') Next (Regular) Block[B4] Leaving: {R1} } Block[B4] - Exit [UnReachable] Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_36() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case < 1: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[0]; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< 1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< 1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_37() { string source = @" public sealed class MyClass { void M(bool result, int input, int other) /*<bind>*/{ switch (input) { case < other: result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(8,20): error CS0150: A constant value is expected // case < other: Diagnostic(ErrorCode.ERR_ConstantExpected, "other").WithLocation(8, 20) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: '< other') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null, IsInvalid) (Syntax: '< other') (InputType: System.Int32, NarrowedType: System.Int32) Value: IParameterReferenceOperation: other (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'other') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B3] Leaving: {R1} } Block[B3] - Exit Predecessors: [B1] [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_38() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case < (true ? 10 : 11): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B5] Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '< (true ? 10 : 11)') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_39() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ switch (input) { case not < (true ? 10 : 11): result = false; break; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '10') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Next (Regular) Block[B5] Block[B4] - Block [UnReachable] Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '11') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 11) (Syntax: '11') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'not < (true ? 10 : 11)') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not < (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Pattern: IRelationalPatternOperation (BinaryOperatorKind.LessThan) (OperationKind.RelationalPattern, Type: null) (Syntax: '< (true ? 10 : 11)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 10, IsImplicit) (Syntax: 'true ? 10 : 11') Leaving: {R2} {R1} Next (Regular) Block[B6] Leaving: {R2} } Block[B6] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = false;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = false') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R1} } Block[B7] - Exit Predecessors: [B5] [B6] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_40() { string source = @" public sealed class MyClass { bool M(char input) /*<bind>*/{ switch (input) { case (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or '_': return true; } return false; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: '(>= 'A' and ... 'z') or '_'') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... 'z') or '_'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '(>= 'A' and ... and <= 'z')') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') RightPattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'') Leaving: {R1} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R1} } Block[B3] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow, CompilerFeature.Patterns)] [Fact] public void SwitchFlow_41() { string source = @" public sealed class MyClass { bool M(object input) /*<bind>*/{ switch (input) { case int or long or ulong: return true; default: return false; } }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsImplicit) (Syntax: 'int or long or ulong') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Object, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long or ulong') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: 'int or long') (InputType: System.Object, NarrowedType: System.Object) LeftPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'int') (InputType: System.Object, NarrowedType: System.Int32, MatchedType: System.Int32) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'long') (InputType: System.Object, NarrowedType: System.Int64, MatchedType: System.Int64) RightPattern: ITypePatternOperation (OperationKind.TypePattern, Type: null) (Syntax: 'ulong') (InputType: System.Object, NarrowedType: System.UInt64, MatchedType: System.UInt64) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Leaving: {R1} Block[B3] - Block Predecessors: [B1] Statements (0) Next (Return) Block[B4] ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Leaving: {R1} } Block[B4] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/VisualBasicTest/Structure/RegionDirectiveStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class RegionDirectiveStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of RegionDirectiveTriviaSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New RegionDirectiveStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function BrokenRegion() As Task Const code = " $$#Region ""Goo"" " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function SimpleRegion() As Task Const code = " {|span:$$#Region ""Goo"" #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "Goo", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionWithNoBanner1() As Task Const code = " {|span:$$#Region #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionWithNoBanner2() As Task Const code = " {|span:$$#Region """" #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <WorkItem(537984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537984")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionEndOfFile() As Task Const code = " Class C End Class {|span:$$#Region #End Region|}" Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class RegionDirectiveStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of RegionDirectiveTriviaSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New RegionDirectiveStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function BrokenRegion() As Task Const code = " $$#Region ""Goo"" " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function SimpleRegion() As Task Const code = " {|span:$$#Region ""Goo"" #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "Goo", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionWithNoBanner1() As Task Const code = " {|span:$$#Region #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionWithNoBanner2() As Task Const code = " {|span:$$#Region """" #End Region|} " Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function <WorkItem(537984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537984")> <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function RegionEndOfFile() As Task Const code = " Class C End Class {|span:$$#Region #End Region|}" Await VerifyBlockSpansAsync(code, Region("span", "#Region", autoCollapse:=False, isDefaultCollapsed:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioProjectFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Telemetry; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export(typeof(VisualStudioProjectFactory))] [Export(typeof(IVsTypeScriptVisualStudioProjectFactory))] internal sealed class VisualStudioProjectFactory : IVsTypeScriptVisualStudioProjectFactory { private const string SolutionContextName = "Solution"; private const string SolutionSessionIdPropertyName = "SolutionSessionID"; private readonly IThreadingContext _threadingContext; private readonly VisualStudioWorkspaceImpl _visualStudioWorkspaceImpl; private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders; private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource; private readonly Shell.IAsyncServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioProjectFactory( IThreadingContext threadingContext, VisualStudioWorkspaceImpl visualStudioWorkspaceImpl, [ImportMany] IEnumerable<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> fileInfoProviders, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _visualStudioWorkspaceImpl = visualStudioWorkspaceImpl; _dynamicFileInfoProviders = fileInfoProviders.AsImmutableOrEmpty(); _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource; _serviceProvider = (Shell.IAsyncServiceProvider)serviceProvider; } public Task<VisualStudioProject> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, CancellationToken cancellationToken) => CreateAndAddToWorkspaceAsync(projectSystemName, language, new VisualStudioProjectCreationInfo(), cancellationToken); public async Task<VisualStudioProject> CreateAndAddToWorkspaceAsync( string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo, CancellationToken cancellationToken) { // HACK: Fetch this service to ensure it's still created on the UI thread; once this is // moved off we'll need to fix up it's constructor to be free-threaded. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _visualStudioWorkspaceImpl.Services.GetRequiredService<VisualStudioMetadataReferenceManager>(); // Since we're on the UI thread here anyways, use that as an opportunity to grab the // IVsSolution object and solution file path. // // ConfigureAwait(true) as we have to come back to the UI thread to do the cast to IVsSolution2. var solution = (IVsSolution2?)await _serviceProvider.GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true); var solutionFilePath = solution != null && ErrorHandler.Succeeded(solution.GetSolutionInfo(out _, out var filePath, out _)) ? filePath : null; await _visualStudioWorkspaceImpl.EnsureDocumentOptionProvidersInitializedAsync(cancellationToken).ConfigureAwait(true); // From this point on, we start mutating the solution. So make us non cancellable. cancellationToken = CancellationToken.None; var id = ProjectId.CreateNewId(projectSystemName); var assemblyName = creationInfo.AssemblyName ?? projectSystemName; // We will use the project system name as the default display name of the project var project = new VisualStudioProject( _visualStudioWorkspaceImpl, _dynamicFileInfoProviders, _hostDiagnosticUpdateSource, id, displayName: projectSystemName, language, assemblyName: assemblyName, compilationOptions: creationInfo.CompilationOptions, filePath: creationInfo.FilePath, parseOptions: creationInfo.ParseOptions); var versionStamp = creationInfo.FilePath != null ? VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath)) : VersionStamp.Create(); _visualStudioWorkspaceImpl.AddProjectToInternalMaps(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName); _visualStudioWorkspaceImpl.ApplyChangeToWorkspace(w => { var projectInfo = ProjectInfo.Create( id, versionStamp, name: projectSystemName, assemblyName: assemblyName, language: language, filePath: creationInfo.FilePath, compilationOptions: creationInfo.CompilationOptions, parseOptions: creationInfo.ParseOptions) .WithTelemetryId(creationInfo.ProjectGuid); // If we don't have any projects and this is our first project being added, then we'll create a new SolutionId if (w.CurrentSolution.ProjectIds.Count == 0) { var solutionSessionId = GetSolutionSessionId(); w.OnSolutionAdded( SolutionInfo.Create( SolutionId.CreateNewId(solutionFilePath), VersionStamp.Create(), solutionFilePath, projects: new[] { projectInfo }, analyzerReferences: w.CurrentSolution.AnalyzerReferences) .WithTelemetryId(solutionSessionId)); } else { w.OnProjectAdded(projectInfo); } _visualStudioWorkspaceImpl.RefreshProjectExistsUIContextForLanguage(language); }); return project; static Guid GetSolutionSessionId() { var dataModelTelemetrySession = TelemetryService.DefaultSession; var solutionContext = dataModelTelemetrySession.GetContext(SolutionContextName); var sessionIdProperty = solutionContext is object ? (string)solutionContext.SharedProperties[SolutionSessionIdPropertyName] : ""; _ = Guid.TryParse(sessionIdProperty, out var solutionSessionId); return solutionSessionId; } } VSTypeScriptVisualStudioProjectWrapper IVsTypeScriptVisualStudioProjectFactory.CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid) { return _threadingContext.JoinableTaskFactory.Run(async () => await ((IVsTypeScriptVisualStudioProjectFactory)this).CreateAndAddToWorkspaceAsync(projectSystemName, language, projectFilePath, hierarchy, projectGuid, CancellationToken.None).ConfigureAwait(false)); } async ValueTask<VSTypeScriptVisualStudioProjectWrapper> IVsTypeScriptVisualStudioProjectFactory.CreateAndAddToWorkspaceAsync( string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, CancellationToken cancellationToken) { var projectInfo = new VisualStudioProjectCreationInfo { FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = projectGuid, }; var visualStudioProject = await this.CreateAndAddToWorkspaceAsync(projectSystemName, language, projectInfo, cancellationToken).ConfigureAwait(false); return new VSTypeScriptVisualStudioProjectWrapper(visualStudioProject); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Telemetry; using Microsoft.VisualStudio.Threading; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { [Export(typeof(VisualStudioProjectFactory))] [Export(typeof(IVsTypeScriptVisualStudioProjectFactory))] internal sealed class VisualStudioProjectFactory : IVsTypeScriptVisualStudioProjectFactory { private const string SolutionContextName = "Solution"; private const string SolutionSessionIdPropertyName = "SolutionSessionID"; private readonly IThreadingContext _threadingContext; private readonly VisualStudioWorkspaceImpl _visualStudioWorkspaceImpl; private readonly ImmutableArray<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> _dynamicFileInfoProviders; private readonly HostDiagnosticUpdateSource _hostDiagnosticUpdateSource; private readonly Shell.IAsyncServiceProvider _serviceProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioProjectFactory( IThreadingContext threadingContext, VisualStudioWorkspaceImpl visualStudioWorkspaceImpl, [ImportMany] IEnumerable<Lazy<IDynamicFileInfoProvider, FileExtensionsMetadata>> fileInfoProviders, HostDiagnosticUpdateSource hostDiagnosticUpdateSource, SVsServiceProvider serviceProvider) { _threadingContext = threadingContext; _visualStudioWorkspaceImpl = visualStudioWorkspaceImpl; _dynamicFileInfoProviders = fileInfoProviders.AsImmutableOrEmpty(); _hostDiagnosticUpdateSource = hostDiagnosticUpdateSource; _serviceProvider = (Shell.IAsyncServiceProvider)serviceProvider; } public Task<VisualStudioProject> CreateAndAddToWorkspaceAsync(string projectSystemName, string language, CancellationToken cancellationToken) => CreateAndAddToWorkspaceAsync(projectSystemName, language, new VisualStudioProjectCreationInfo(), cancellationToken); public async Task<VisualStudioProject> CreateAndAddToWorkspaceAsync( string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo, CancellationToken cancellationToken) { // HACK: Fetch this service to ensure it's still created on the UI thread; once this is // moved off we'll need to fix up it's constructor to be free-threaded. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); _visualStudioWorkspaceImpl.Services.GetRequiredService<VisualStudioMetadataReferenceManager>(); // Since we're on the UI thread here anyways, use that as an opportunity to grab the // IVsSolution object and solution file path. // // ConfigureAwait(true) as we have to come back to the UI thread to do the cast to IVsSolution2. var solution = (IVsSolution2?)await _serviceProvider.GetServiceAsync(typeof(SVsSolution)).ConfigureAwait(true); var solutionFilePath = solution != null && ErrorHandler.Succeeded(solution.GetSolutionInfo(out _, out var filePath, out _)) ? filePath : null; await _visualStudioWorkspaceImpl.EnsureDocumentOptionProvidersInitializedAsync(cancellationToken).ConfigureAwait(true); // From this point on, we start mutating the solution. So make us non cancellable. cancellationToken = CancellationToken.None; var id = ProjectId.CreateNewId(projectSystemName); var assemblyName = creationInfo.AssemblyName ?? projectSystemName; // We will use the project system name as the default display name of the project var project = new VisualStudioProject( _visualStudioWorkspaceImpl, _dynamicFileInfoProviders, _hostDiagnosticUpdateSource, id, displayName: projectSystemName, language, assemblyName: assemblyName, compilationOptions: creationInfo.CompilationOptions, filePath: creationInfo.FilePath, parseOptions: creationInfo.ParseOptions); var versionStamp = creationInfo.FilePath != null ? VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath)) : VersionStamp.Create(); _visualStudioWorkspaceImpl.AddProjectToInternalMaps(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName); _visualStudioWorkspaceImpl.ApplyChangeToWorkspace(w => { var projectInfo = ProjectInfo.Create( id, versionStamp, name: projectSystemName, assemblyName: assemblyName, language: language, filePath: creationInfo.FilePath, compilationOptions: creationInfo.CompilationOptions, parseOptions: creationInfo.ParseOptions) .WithTelemetryId(creationInfo.ProjectGuid); // If we don't have any projects and this is our first project being added, then we'll create a new SolutionId if (w.CurrentSolution.ProjectIds.Count == 0) { var solutionSessionId = GetSolutionSessionId(); w.OnSolutionAdded( SolutionInfo.Create( SolutionId.CreateNewId(solutionFilePath), VersionStamp.Create(), solutionFilePath, projects: new[] { projectInfo }, analyzerReferences: w.CurrentSolution.AnalyzerReferences) .WithTelemetryId(solutionSessionId)); } else { w.OnProjectAdded(projectInfo); } _visualStudioWorkspaceImpl.RefreshProjectExistsUIContextForLanguage(language); }); return project; static Guid GetSolutionSessionId() { var dataModelTelemetrySession = TelemetryService.DefaultSession; var solutionContext = dataModelTelemetrySession.GetContext(SolutionContextName); var sessionIdProperty = solutionContext is object ? (string)solutionContext.SharedProperties[SolutionSessionIdPropertyName] : ""; _ = Guid.TryParse(sessionIdProperty, out var solutionSessionId); return solutionSessionId; } } VSTypeScriptVisualStudioProjectWrapper IVsTypeScriptVisualStudioProjectFactory.CreateAndAddToWorkspace(string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid) { return _threadingContext.JoinableTaskFactory.Run(async () => await ((IVsTypeScriptVisualStudioProjectFactory)this).CreateAndAddToWorkspaceAsync(projectSystemName, language, projectFilePath, hierarchy, projectGuid, CancellationToken.None).ConfigureAwait(false)); } async ValueTask<VSTypeScriptVisualStudioProjectWrapper> IVsTypeScriptVisualStudioProjectFactory.CreateAndAddToWorkspaceAsync( string projectSystemName, string language, string projectFilePath, IVsHierarchy hierarchy, Guid projectGuid, CancellationToken cancellationToken) { var projectInfo = new VisualStudioProjectCreationInfo { FilePath = projectFilePath, Hierarchy = hierarchy, ProjectGuid = projectGuid, }; var visualStudioProject = await this.CreateAndAddToWorkspaceAsync(projectSystemName, language, projectInfo, cancellationToken).ConfigureAwait(false); return new VSTypeScriptVisualStudioProjectWrapper(visualStudioProject); } } }
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/Interactive/HostProcess/App.config
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> </runtime> </configuration>
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> </runtime> </configuration>
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/SelectBlockTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class SelectBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterSelectKeyword() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() Select goo End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() Select goo Case End Select End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterSelectCaseKeyword() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() Select Case goo End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() Select Case goo Case End Select End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedDo() VerifyStatementEndConstructApplied( before:="Class C Sub S Select Case 1 Case 1 Select 1 End Select End Sub End Class", beforeCaret:={4, -1}, after:="Class C Sub S Select Case 1 Case 1 Select 1 Case End Select End Select End Sub End Class", afterCaret:={5, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock() VerifyStatementEndConstructNotApplied( text:="Class C Sub S dim x = Select 1 End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock01() VerifyStatementEndConstructNotApplied( text:="Class EC Sub T Select 1 Case 1 End Sub End Class", caret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock02() VerifyStatementEndConstructNotApplied( text:="Class EC Select 1 End Class", caret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyReCommitSelectBlock() VerifyStatementEndConstructNotApplied( text:="Class C Sub S Select Case 1 Case 1 End Select End Sub End Class", caret:={2, -1}) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.EndConstructGeneration <[UseExportProvider]> Public Class SelectBlockTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterSelectKeyword() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() Select goo End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() Select goo Case End Select End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterSelectCaseKeyword() VerifyStatementEndConstructApplied( before:="Class c1 Sub goo() Select Case goo End Sub End Class", beforeCaret:={2, -1}, after:="Class c1 Sub goo() Select Case goo Case End Select End Sub End Class", afterCaret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyNestedDo() VerifyStatementEndConstructApplied( before:="Class C Sub S Select Case 1 Case 1 Select 1 End Select End Sub End Class", beforeCaret:={4, -1}, after:="Class C Sub S Select Case 1 Case 1 Select 1 Case End Select End Select End Sub End Class", afterCaret:={5, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock() VerifyStatementEndConstructNotApplied( text:="Class C Sub S dim x = Select 1 End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock01() VerifyStatementEndConstructNotApplied( text:="Class EC Sub T Select 1 Case 1 End Sub End Class", caret:={3, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyInvalidSelectBlock02() VerifyStatementEndConstructNotApplied( text:="Class EC Select 1 End Class", caret:={1, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub VerifyReCommitSelectBlock() VerifyStatementEndConstructNotApplied( text:="Class C Sub S Select Case 1 Case 1 End Select End Sub End Class", caret:={2, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
55,318
Move IAddMissingImportsFeatureService to use OOP
IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
ryzngard
2021-07-31T21:49:49Z
2021-08-05T08:23:56Z
11776736ea4447733d3b11850c211d998c39b01d
b57c1f89c1483da8704cde7b535a20fd029748db
Move IAddMissingImportsFeatureService to use OOP. IAddMissingImportsFeatureService wraps IAddImportFeatureService with some logic for reducing fixes that will be taken. The work to get diagnostics was previously done inproc, which can be expensive. This moves that work to IAddImportFeatureService via a new `GetUniqueFixesAsync` api and utilizes OOP when possible
./src/EditorFeatures/Core/GoToDefinition/GoToSymbolContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal class GoToSymbolContext { private readonly object _gate = new(); private readonly MultiDictionary<string, DefinitionItem> _items = new(); public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken) { Document = document; Position = position; CancellationToken = cancellationToken; } public Document Document { get; } public int Position { get; } public CancellationToken CancellationToken { get; } public TextSpan Span { get; set; } internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items) { if (_items.ContainsKey(key)) { // Multidictionary valuesets are structs so we can't // just check for null items = _items[key]; return true; } else { items = null; return false; } } public void AddItem(string key, DefinitionItem item) { lock (_gate) { _items.Add(key, item); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal class GoToSymbolContext { private readonly object _gate = new(); private readonly MultiDictionary<string, DefinitionItem> _items = new(); public GoToSymbolContext(Document document, int position, CancellationToken cancellationToken) { Document = document; Position = position; CancellationToken = cancellationToken; } public Document Document { get; } public int Position { get; } public CancellationToken CancellationToken { get; } public TextSpan Span { get; set; } internal bool TryGetItems(string key, out IEnumerable<DefinitionItem> items) { if (_items.ContainsKey(key)) { // Multidictionary valuesets are structs so we can't // just check for null items = _items[key]; return true; } else { items = null; return false; } } public void AddItem(string key, DefinitionItem item) { lock (_gate) { _items.Add(key, item); } } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Implementation/AddImports/AbstractAddImportsPasteCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.AddMissingImports; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports { internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs> { /// <summary> /// The command handler display name /// </summary> public abstract string DisplayName { get; } /// <summary> /// The thread await dialog text shown to the user if the operation takes a long time /// </summary> protected abstract string DialogText { get; } private readonly IThreadingContext _threadingContext; public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Check that the feature is enabled before doing any work var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste); // If the feature is explicitly disabled we can exit early if (optionValue.HasValue && !optionValue.Value) { nextCommandHandler(); return; } // Capture the pre-paste caret position var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretPosition.HasValue) { nextCommandHandler(); return; } // Create a tracking span from the pre-paste caret position that will grow as text is inserted. var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive); // Perform the paste command before adding imports nextCommandHandler(); if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, executionContext, optionValue, trackingSpan); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private void ExecuteCommandWorker( PasteCommandArgs args, CommandExecutionContext executionContext, bool? optionValue, ITrackingSpan trackingSpan) { if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace()) { return; } // Don't perform work if we're inside the interactive window if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer)) { return; } // Applying the post-paste snapshot to the tracking span gives us the span of pasted text. var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var sourceTextContainer = args.SubjectBuffer.AsTextContainer(); if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { return; } var document = sourceTextContainer.GetOpenDocumentInCurrentContext(); if (document is null) { return; } // Enable by default unless the user has explicitly disabled in the settings var disabled = optionValue.HasValue && !optionValue.Value; if (disabled) { return; } using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText); var cancellationToken = executionContext.OperationContext.UserCancellationToken; // We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is // intended to tell us how long we're blocking the user from typing with this action. using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>(); #pragma warning disable VSTHRD102 // Implement internal logic asynchronously var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken)); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously if (updatedDocument is null) { return; } workspace.TryApplyChanges(updatedDocument.Project.Solution); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.AddMissingImports; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.AddImports { internal abstract class AbstractAddImportsPasteCommandHandler : IChainedCommandHandler<PasteCommandArgs> { /// <summary> /// The command handler display name /// </summary> public abstract string DisplayName { get; } /// <summary> /// The thread await dialog text shown to the user if the operation takes a long time /// </summary> protected abstract string DialogText { get; } private readonly IThreadingContext _threadingContext; public AbstractAddImportsPasteCommandHandler(IThreadingContext threadingContext) => _threadingContext = threadingContext; public CommandState GetCommandState(PasteCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); public void ExecuteCommand(PasteCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // Check that the feature is enabled before doing any work var optionValue = args.SubjectBuffer.GetOptionalFeatureOnOffOption(FeatureOnOffOptions.AddImportsOnPaste); // If the feature is not explicitly enabled we can exit early if (optionValue != true) { nextCommandHandler(); return; } // Capture the pre-paste caret position var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer); if (!caretPosition.HasValue) { nextCommandHandler(); return; } // Create a tracking span from the pre-paste caret position that will grow as text is inserted. var trackingSpan = caretPosition.Value.Snapshot.CreateTrackingSpan(caretPosition.Value.Position, 0, SpanTrackingMode.EdgeInclusive); // Perform the paste command before adding imports nextCommandHandler(); if (executionContext.OperationContext.UserCancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, executionContext, trackingSpan); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private void ExecuteCommandWorker( PasteCommandArgs args, CommandExecutionContext executionContext, ITrackingSpan trackingSpan) { if (!args.SubjectBuffer.CanApplyChangeDocumentToWorkspace()) { return; } // Don't perform work if we're inside the interactive window if (args.TextView.IsNotSurfaceBufferOfTextView(args.SubjectBuffer)) { return; } // Applying the post-paste snapshot to the tracking span gives us the span of pasted text. var snapshotSpan = trackingSpan.GetSpan(args.SubjectBuffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var sourceTextContainer = args.SubjectBuffer.AsTextContainer(); if (!Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { return; } var document = sourceTextContainer.GetOpenDocumentInCurrentContext(); if (document is null) { return; } using var _ = executionContext.OperationContext.AddScope(allowCancellation: true, DialogText); var cancellationToken = executionContext.OperationContext.UserCancellationToken; // We're going to log the same thing on success or failure since this blocks the UI thread. This measurement is // intended to tell us how long we're blocking the user from typing with this action. using var blockLogger = Logger.LogBlock(FunctionId.CommandHandler_Paste_ImportsOnPaste, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken); var addMissingImportsService = document.GetRequiredLanguageService<IAddMissingImportsFeatureService>(); #pragma warning disable VSTHRD102 // Implement internal logic asynchronously var updatedDocument = _threadingContext.JoinableTaskFactory.Run(() => addMissingImportsService.AddMissingImportsAsync(document, textSpan, cancellationToken)); #pragma warning restore VSTHRD102 // Implement internal logic asynchronously if (updatedDocument is null) { return; } workspace.TryApplyChanges(updatedDocument.Project.Solution); } } }
1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/CSharp/Impl/Options/AdvancedOptionPageControl.xaml.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is now enabled by default. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to be enabled by default return true; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => true); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Windows; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Options; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.ValidateFormatString; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.ColorSchemes; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { internal partial class AdvancedOptionPageControl : AbstractOptionPageControl { private readonly ColorSchemeApplier _colorSchemeApplier; public AdvancedOptionPageControl(OptionStore optionStore, IComponentModel componentModel, IExperimentationService experimentationService) : base(optionStore) { _colorSchemeApplier = componentModel.GetService<ColorSchemeApplier>(); InitializeComponent(); BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.CSharp); BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.CSharp); BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.CSharp); BindToOption(Enable_navigation_to_decompiled_sources, FeatureOnOffOptions.NavigateToDecompiledSources); BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit); BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics); BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds); BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, () => { // If the option has not been set by the user, check if the option to remove unused references // is enabled from experimentation. If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) ?? false; }); BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp); BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.CSharp); BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp); BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp); BindToOption(AddUsingsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.CSharp, () => { // This option used to be backed by an experimentation flag but is no longer. // Having the option still a bool? keeps us from running into storage related issues, // but if the option was stored as null we want it to respect this default return false; }); BindToOption(Split_string_literals_on_enter, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(EnterOutliningMode, FeatureOnOffOptions.Outlining, LanguageNames.CSharp); BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.CSharp); BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.CSharp); BindToOption(Fade_out_unused_usings, FadingOptions.FadeOutUnusedImports, LanguageNames.CSharp); BindToOption(Fade_out_unreachable_code, FadingOptions.FadeOutUnreachableCode, LanguageNames.CSharp); BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.CSharp); BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.CSharp); BindToOption(GenerateXmlDocCommentsForTripleSlash, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.CSharp); BindToOption(InsertSlashSlashAtTheStartOfNewLinesWhenWritingSingleLineComments, SplitStringLiteralOptions.Enabled, LanguageNames.CSharp); BindToOption(InsertAsteriskAtTheStartOfNewLinesWhenWritingBlockComments, FeatureOnOffOptions.AutoInsertBlockCommentStartString, LanguageNames.CSharp); BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.CSharp); BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.CSharp); BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.CSharp); BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.CSharp); BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.CSharp); BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.CSharp); BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, () => { // If the option has not been set by the user, check if the option is enabled from experimentation. // If so, default to that. Otherwise default to disabled return experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace) ?? false; }); BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.CSharp); BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.CSharp); BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.CSharp); BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.CSharp); BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.CSharp); BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.CSharp); BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.CSharp); BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.CSharp); BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.CSharp); BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.CSharp); BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme); BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1); BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.CSharp); BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.CSharp); BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.CSharp); BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.CSharp); BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.CSharp); BindToOption(DisplayInlineTypeHints, InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); BindToOption(ShowHintsForVariablesWithInferredTypes, InlineHintsOptions.ForImplicitVariableTypes, LanguageNames.CSharp); BindToOption(ShowHintsForLambdaParameterTypes, InlineHintsOptions.ForLambdaParameterTypes, LanguageNames.CSharp); BindToOption(ShowHintsForImplicitObjectCreation, InlineHintsOptions.ForImplicitObjectCreation, LanguageNames.CSharp); // Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.CSharp, () => true); } // Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, // we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. internal override void OnLoad() { var isSupportedTheme = _colorSchemeApplier.IsSupportedTheme(); var isThemeCustomized = _colorSchemeApplier.IsThemeCustomized(); Editor_color_scheme.Visibility = isSupportedTheme ? Visibility.Visible : Visibility.Collapsed; Customized_Theme_Warning.Visibility = isSupportedTheme && isThemeCustomized ? Visibility.Visible : Visibility.Collapsed; Custom_VS_Theme_Warning.Visibility = isSupportedTheme ? Visibility.Collapsed : Visibility.Visible; UpdatePullDiagnosticsOptions(); UpdateInlineHintsOptions(); base.OnLoad(); } private void UpdatePullDiagnosticsOptions() { var normalPullDiagnosticsOption = OptionStore.GetOption(InternalDiagnosticsOptions.NormalDiagnosticMode); Enable_pull_diagnostics_experimental_requires_restart.IsChecked = GetDiagnosticModeCheckboxValue(normalPullDiagnosticsOption); Enable_Razor_pull_diagnostics_experimental_requires_restart.IsChecked = OptionStore.GetOption(InternalDiagnosticsOptions.RazorDiagnosticMode) == DiagnosticMode.Pull; static bool? GetDiagnosticModeCheckboxValue(DiagnosticMode mode) { return mode switch { DiagnosticMode.Push => false, DiagnosticMode.Pull => true, DiagnosticMode.Default => null, _ => throw new System.ArgumentException("unknown diagnostic mode"), }; } } private void Enable_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void Enable_pull_diagnostics_experimental_requires_restart_Indeterminate(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.NormalDiagnosticMode, DiagnosticMode.Default); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Pull); UpdatePullDiagnosticsOptions(); } private void Enable_Razor_pull_diagnostics_experimental_requires_restart_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InternalDiagnosticsOptions.RazorDiagnosticMode, DiagnosticMode.Push); UpdatePullDiagnosticsOptions(); } private void UpdateInlineHintsOptions() { var enabledForParameters = this.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp); ShowHintsForLiterals.IsEnabled = enabledForParameters; ShowHintsForNewExpressions.IsEnabled = enabledForParameters; ShowHintsForEverythingElse.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters; SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters; var enabledForTypes = this.OptionStore.GetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp); ShowHintsForVariablesWithInferredTypes.IsEnabled = enabledForTypes; ShowHintsForLambdaParameterTypes.IsEnabled = enabledForTypes; ShowHintsForImplicitObjectCreation.IsEnabled = enabledForTypes; } private void DisplayInlineParameterNameHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineParameterNameHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Checked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, true); UpdateInlineHintsOptions(); } private void DisplayInlineTypeHints_Unchecked(object sender, RoutedEventArgs e) { this.OptionStore.SetOption(InlineHintsOptions.EnabledForTypes, LanguageNames.CSharp, false); UpdateInlineHintsOptions(); } } }
1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpAddMissingUsingsOnPaste.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest { public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste)) { } protected override string LanguageName => LanguageNames.CSharp; [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyDisabled() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyEnabledWithNull() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyAddImportsOnPaste() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); using var telemetry = VisualStudio.EnableTestTelemetryChannel(); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste"); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Editor.Shared.Options; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpAddMissingUsingsOnPaste : AbstractEditorTest { public CSharpAddMissingUsingsOnPaste(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpAddMissingUsingsOnPaste)) { } protected override string LanguageName => LanguageNames.CSharp; [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyDisabled() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "False"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyDisabledWithNull() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, valueString: null); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.AddMissingImports)] public void VerifyAddImportsOnPaste() { var project = new Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.AddFile(project, "Example.cs", contents: @" public class Example { } "); SetUpEditor(@" using System; class Program { static void Main(string[] args) { } $$ }"); using var telemetry = VisualStudio.EnableTestTelemetryChannel(); VisualStudio.Workspace.SetFeatureOption(FeatureOnOffOptions.AddImportsOnPaste.Feature, FeatureOnOffOptions.AddImportsOnPaste.Name, LanguageNames.CSharp, "True"); VisualStudio.Editor.Paste(@"Task DoThingAsync() => Task.CompletedTask;"); VisualStudio.Editor.Verify.TextContains(@" using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { } Task DoThingAsync() => Task.CompletedTask; }"); telemetry.VerifyFired("vs/ide/vbcs/commandhandler/paste/importsonpaste"); } } }
1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageControl.xaml.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.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is now enabled by default. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to be enabled by default Return True End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled Return True End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() 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.Windows Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.DocumentationComments Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor.Implementation.SplitComment Imports Microsoft.CodeAnalysis.Editor.Options Imports Microsoft.CodeAnalysis.Editor.Shared.Options Imports Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions Imports Microsoft.CodeAnalysis.Experiments Imports Microsoft.CodeAnalysis.ExtractMethod Imports Microsoft.CodeAnalysis.Fading Imports Microsoft.CodeAnalysis.ImplementType Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.QuickInfo Imports Microsoft.CodeAnalysis.Remote Imports Microsoft.CodeAnalysis.SolutionCrawler Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.ValidateFormatString Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.ColorSchemes Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Friend Class AdvancedOptionPageControl Private ReadOnly _colorSchemeApplier As ColorSchemeApplier Public Sub New(optionStore As OptionStore, componentModel As IComponentModel, experimentationService As IExperimentationService) MyBase.New(optionStore) _colorSchemeApplier = componentModel.GetService(Of ColorSchemeApplier)() InitializeComponent() ' Keep this code in sync with the actual order options appear in Tools | Options ' Analysis BindToOption(Background_analysis_scope_active_file, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.ActiveFile, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_open_files, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.OpenFilesAndProjects, LanguageNames.VisualBasic) BindToOption(Background_analysis_scope_full_solution, SolutionCrawlerOptions.BackgroundAnalysisScopeOption, BackgroundAnalysisScope.FullSolution, LanguageNames.VisualBasic) BindToOption(Use_64bit_analysis_process, RemoteHostOptions.OOP64Bit) BindToOption(Enable_file_logging_for_diagnostics, InternalDiagnosticsOptions.EnableFileLoggingForDiagnostics) BindToOption(Skip_analyzers_for_implicitly_triggered_builds, FeatureOnOffOptions.SkipAnalyzersForImplicitlyTriggeredBuilds) BindToOption(Show_Remove_Unused_References_command_in_Solution_Explorer_experimental, FeatureOnOffOptions.OfferRemoveUnusedReferences, Function() ' If the option has Not been set by the user, check if the option to remove unused references ' Is enabled from experimentation. If so, default to that. Otherwise default to disabled If experimentationService Is Nothing Then Return False End If Return experimentationService.IsExperimentEnabled(WellKnownExperimentNames.RemoveUnusedReferences) End Function) ' Import directives BindToOption(PlaceSystemNamespaceFirst, GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.VisualBasic) BindToOption(SeparateImportGroups, GenerationOptions.SeparateImportDirectiveGroups, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic) BindToOption(SuggestForTypesInNuGetPackages, SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic) BindToOption(AddMissingImportsOnPaste, FeatureOnOffOptions.AddImportsOnPaste, LanguageNames.VisualBasic, Function() ' This option used to be backed by an experimentation flag but Is no longer. ' Having the option still a bool? keeps us from running into storage related issues, ' but if the option was stored as null we want it to respect this default Return False End Function) ' Highlighting BindToOption(EnableHighlightReferences, FeatureOnOffOptions.ReferenceHighlighting, LanguageNames.VisualBasic) BindToOption(EnableHighlightKeywords, FeatureOnOffOptions.KeywordHighlighting, LanguageNames.VisualBasic) ' Outlining BindToOption(EnableOutlining, FeatureOnOffOptions.Outlining, LanguageNames.VisualBasic) BindToOption(DisplayLineSeparators, FeatureOnOffOptions.LineSeparator, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_declaration_level_constructs, BlockStructureOptions.ShowOutliningForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_code_level_constructs, BlockStructureOptions.ShowOutliningForCodeLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_outlining_for_comments_and_preprocessor_regions, BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions, LanguageNames.VisualBasic) BindToOption(Collapse_regions_when_collapsing_to_definitions, BlockStructureOptions.CollapseRegionsWhenCollapsingToDefinitions, LanguageNames.VisualBasic) ' Fading BindToOption(Fade_out_unused_imports, FadingOptions.FadeOutUnusedImports, LanguageNames.VisualBasic) ' Block structure guides BindToOption(Show_guides_for_declaration_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForDeclarationLevelConstructs, LanguageNames.VisualBasic) BindToOption(Show_guides_for_code_level_constructs, BlockStructureOptions.ShowBlockStructureGuidesForCodeLevelConstructs, LanguageNames.VisualBasic) ' Comments BindToOption(GenerateXmlDocCommentsForTripleApostrophes, DocumentationCommentOptions.AutoXmlDocCommentGeneration, LanguageNames.VisualBasic) BindToOption(InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments, SplitCommentOptions.Enabled, LanguageNames.VisualBasic) ' Editor help BindToOption(EnableEndConstruct, FeatureOnOffOptions.EndConstruct, LanguageNames.VisualBasic) BindToOption(EnableLineCommit, FeatureOnOffOptions.PrettyListing, LanguageNames.VisualBasic) BindToOption(AutomaticInsertionOfInterfaceAndMustOverrideMembers, FeatureOnOffOptions.AutomaticInsertionOfAbstractOrInterfaceMembers, LanguageNames.VisualBasic) BindToOption(RenameTrackingPreview, FeatureOnOffOptions.RenameTrackingPreview, LanguageNames.VisualBasic) BindToOption(ShowRemarksInQuickInfo, QuickInfoOptions.ShowRemarksInQuickInfo, LanguageNames.VisualBasic) BindToOption(Report_invalid_placeholders_in_string_dot_format_calls, ValidateFormatStringOption.ReportInvalidPlaceholdersInStringDotFormatCalls, LanguageNames.VisualBasic) BindToOption(Underline_reassigned_variables, ClassificationOptions.ClassifyReassignedVariables, LanguageNames.VisualBasic) ' Go To Definition BindToOption(NavigateToObjectBrowser, VisualStudioNavigationOptions.NavigateToObjectBrowser, LanguageNames.VisualBasic) BindToOption(Enable_all_features_in_opened_files_from_source_generators, SourceGeneratedFileManager.EnableOpeningInWorkspace, Function() ' If the option has not been set by the user, check if the option Is enabled from experimentation. ' If so, default to that. Otherwise default to disabled Return If(experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.SourceGeneratorsEnableOpeningInWorkspace), False) End Function) ' Regular expressions BindToOption(Colorize_regular_expressions, RegularExpressionsOptions.ColorizeRegexPatterns, LanguageNames.VisualBasic) BindToOption(Report_invalid_regular_expressions, RegularExpressionsOptions.ReportInvalidRegexPatterns, LanguageNames.VisualBasic) BindToOption(Highlight_related_components_under_cursor, RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, LanguageNames.VisualBasic) BindToOption(Show_completion_list, RegularExpressionsOptions.ProvideRegexCompletions, LanguageNames.VisualBasic) ' Editor color scheme BindToOption(Editor_color_scheme, ColorSchemeOptions.ColorScheme) ' Extract method BindToOption(DontPutOutOrRefOnStruct, ExtractMethodOptions.DontPutOutOrRefOnStruct, LanguageNames.VisualBasic) ' Implement Interface or Abstract Class BindToOption(with_other_members_of_the_same_kind, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.WithOtherMembersOfTheSameKind, LanguageNames.VisualBasic) BindToOption(at_the_end, ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd, LanguageNames.VisualBasic) BindToOption(prefer_throwing_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferThrowingProperties, LanguageNames.VisualBasic) BindToOption(prefer_auto_properties, ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties, LanguageNames.VisualBasic) ' Inline hints BindToOption(DisplayAllHintsWhilePressingAltF1, InlineHintsOptions.DisplayAllHintsWhilePressingAltF1) BindToOption(ColorHints, InlineHintsOptions.ColorHints, LanguageNames.VisualBasic) BindToOption(DisplayInlineParameterNameHints, InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForLiterals, InlineHintsOptions.ForLiteralParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForNewExpressions, InlineHintsOptions.ForObjectCreationParameters, LanguageNames.VisualBasic) BindToOption(ShowHintsForEverythingElse, InlineHintsOptions.ForOtherParameters, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNameMatchesTheMethodsIntent, InlineHintsOptions.SuppressForParametersThatMatchMethodIntent, LanguageNames.VisualBasic) BindToOption(SuppressHintsWhenParameterNamesDifferOnlyBySuffix, InlineHintsOptions.SuppressForParametersThatDifferOnlyBySuffix, LanguageNames.VisualBasic) BindToOption(ShowInheritanceMargin, FeatureOnOffOptions.ShowInheritanceMargin, LanguageNames.VisualBasic, Function() ' Leave the null converter here to make sure if the option value is get from the storage (if it is null), the feature will be enabled Return True End Function) End Sub ' Since this dialog is constructed once for the lifetime of the application and VS Theme can be changed after the application has started, ' we need to update the visibility of our combobox and warnings based on the current VS theme before being rendered. Friend Overrides Sub OnLoad() Dim isSupportedTheme = _colorSchemeApplier.IsSupportedTheme() Dim isCustomized = _colorSchemeApplier.IsThemeCustomized() Editor_color_scheme.Visibility = If(isSupportedTheme, Visibility.Visible, Visibility.Collapsed) Customized_Theme_Warning.Visibility = If(isSupportedTheme AndAlso isCustomized, Visibility.Visible, Visibility.Collapsed) Custom_VS_Theme_Warning.Visibility = If(isSupportedTheme, Visibility.Collapsed, Visibility.Visible) UpdateInlineHintsOptions() MyBase.OnLoad() End Sub Private Sub UpdateInlineHintsOptions() Dim enabledForParameters = Me.OptionStore.GetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic) <> False ShowHintsForLiterals.IsEnabled = enabledForParameters ShowHintsForNewExpressions.IsEnabled = enabledForParameters ShowHintsForEverythingElse.IsEnabled = enabledForParameters SuppressHintsWhenParameterNameMatchesTheMethodsIntent.IsEnabled = enabledForParameters SuppressHintsWhenParameterNamesDifferOnlyBySuffix.IsEnabled = enabledForParameters End Sub Private Sub DisplayInlineParameterNameHints_Checked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, True) UpdateInlineHintsOptions() End Sub Private Sub DisplayInlineParameterNameHints_Unchecked() Me.OptionStore.SetOption(InlineHintsOptions.EnabledForParameters, LanguageNames.VisualBasic, False) UpdateInlineHintsOptions() End Sub End Class End Namespace
1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/LoopKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class LoopKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotAfterStatementTest() VerifyRecommendationsMissing(<MethodBody> Dim x |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoStatementTest() VerifyRecommendationsContain(<MethodBody> Do |</MethodBody>, "Loop", "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoUntilStatementTest() VerifyRecommendationsContain(<MethodBody> Do Until True |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopUntilNotAfterDoUntilStatementTest() VerifyRecommendationsMissing(<MethodBody> Do Until True |</MethodBody>, "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInDoLoopUntilBlockTest() VerifyRecommendationsMissing(<MethodBody> Do | Loop Until True</MethodBody>, "Loop") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class LoopKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInMethodBodyTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotAfterStatementTest() VerifyRecommendationsMissing(<MethodBody> Dim x |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoStatementTest() VerifyRecommendationsContain(<MethodBody> Do |</MethodBody>, "Loop", "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopAfterDoUntilStatementTest() VerifyRecommendationsContain(<MethodBody> Do Until True |</MethodBody>, "Loop") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopUntilNotAfterDoUntilStatementTest() VerifyRecommendationsMissing(<MethodBody> Do Until True |</MethodBody>, "Loop Until", "Loop While") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub LoopNotInDoLoopUntilBlockTest() VerifyRecommendationsMissing(<MethodBody> Do | Loop Until True</MethodBody>, "Loop") End Sub End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/AsyncCompletionLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Internal.Log; namespace Microsoft.CodeAnalysis { internal class AsyncCompletionLogger { private static readonly LogAggregator s_logAggregator = new(); internal enum ActionInfo { // For type import completion SessionWithTypeImportCompletionEnabled, CommitWithTypeImportCompletionEnabled, // For targeted type completion SessionHasTargetTypeFilterEnabled, // TargetTypeFilterChosenInSession / SessionContainsTargetTypeFilter indicates % of the time // the Target Type Completion Filter is chosen of the sessions offering it. SessionContainsTargetTypeFilter, TargetTypeFilterChosenInSession, // CommitItemWithTargetTypeFilter / CommitWithTargetTypeCompletionExperimentEnabled indicates // % of the time a completion item is committed that could have been picked via the Target Type // Completion Filter. CommitWithTargetTypeCompletionExperimentEnabled, CommitItemWithTargetTypeFilter, } internal static void LogSessionWithTypeImportCompletionEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionWithTypeImportCompletionEnabled); internal static void LogCommitWithTypeImportCompletionEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitWithTypeImportCompletionEnabled); internal static void LogCommitWithTargetTypeCompletionExperimentEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitWithTargetTypeCompletionExperimentEnabled); internal static void LogCommitItemWithTargetTypeFilter() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitItemWithTargetTypeFilter); internal static void LogSessionContainsTargetTypeFilter() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionContainsTargetTypeFilter); internal static void LogTargetTypeFilterChosenInSession() => s_logAggregator.IncreaseCount((int)ActionInfo.TargetTypeFilterChosenInSession); internal static void LogSessionHasTargetTypeFilterEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionHasTargetTypeFilterEnabled); internal static void ReportTelemetry() { Logger.Log(FunctionId.Intellisense_AsyncCompletion_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_logAggregator) { var mergeInfo = ((ActionInfo)kv.Key).ToString("f"); m[mergeInfo] = kv.Value.GetCount(); } })); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Internal.Log; namespace Microsoft.CodeAnalysis { internal class AsyncCompletionLogger { private static readonly LogAggregator s_logAggregator = new(); internal enum ActionInfo { // For type import completion SessionWithTypeImportCompletionEnabled, CommitWithTypeImportCompletionEnabled, // For targeted type completion SessionHasTargetTypeFilterEnabled, // TargetTypeFilterChosenInSession / SessionContainsTargetTypeFilter indicates % of the time // the Target Type Completion Filter is chosen of the sessions offering it. SessionContainsTargetTypeFilter, TargetTypeFilterChosenInSession, // CommitItemWithTargetTypeFilter / CommitWithTargetTypeCompletionExperimentEnabled indicates // % of the time a completion item is committed that could have been picked via the Target Type // Completion Filter. CommitWithTargetTypeCompletionExperimentEnabled, CommitItemWithTargetTypeFilter, } internal static void LogSessionWithTypeImportCompletionEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionWithTypeImportCompletionEnabled); internal static void LogCommitWithTypeImportCompletionEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitWithTypeImportCompletionEnabled); internal static void LogCommitWithTargetTypeCompletionExperimentEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitWithTargetTypeCompletionExperimentEnabled); internal static void LogCommitItemWithTargetTypeFilter() => s_logAggregator.IncreaseCount((int)ActionInfo.CommitItemWithTargetTypeFilter); internal static void LogSessionContainsTargetTypeFilter() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionContainsTargetTypeFilter); internal static void LogTargetTypeFilterChosenInSession() => s_logAggregator.IncreaseCount((int)ActionInfo.TargetTypeFilterChosenInSession); internal static void LogSessionHasTargetTypeFilterEnabled() => s_logAggregator.IncreaseCount((int)ActionInfo.SessionHasTargetTypeFilterEnabled); internal static void ReportTelemetry() { Logger.Log(FunctionId.Intellisense_AsyncCompletion_Data, KeyValueLogMessage.Create(m => { foreach (var kv in s_logAggregator) { var mergeInfo = ((ActionInfo)kv.Key).ToString("f"); m[mergeInfo] = kv.Value.GetCount(); } })); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/RefKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RefKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 TestNotAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterIn() { await VerifyAbsenceAsync( @"interface IGoo<in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"interface IGoo<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAngle() { await VerifyAbsenceAsync( @"delegate void D<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"delegate void D<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotRefBaseListAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGenericMethod() { await VerifyAbsenceAsync( @"interface IGoo { void Goo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRef() { await VerifyAbsenceAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOut() { await VerifyAbsenceAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThisConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C():this($$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThisConstructorInitializerNamedArgument() { await VerifyKeywordAsync( @"class C { public C():this(Goo:$$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBaseConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C():base($$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBaseConstructorInitializerNamedArgument() { await VerifyKeywordAsync( @"class C { public C():base(5, Goo:$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOperator() { await VerifyAbsenceAsync( @"class C { static int operator +($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDestructor() { await VerifyAbsenceAsync( @"class C { ~C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexer() { await VerifyAbsenceAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterOpenParen() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefParam() { await VerifyAbsenceAsync( @"class C { void Goo() { new Bar(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOutParam() { await VerifyAbsenceAsync( @"class C { void Goo() { new Bar(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterComma() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterSecondComma() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz, quux, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterSecondNamedParam() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz: 4, quux: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationExpression() { await VerifyKeywordAsync( @"class C { void Goo() { Bar($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterComma() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterSecondComma() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz, quux, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterSecondNamedParam() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz: 4, quux: $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = (ref int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefParameterList() { var text = @"Class c { /// <see cref=""main($$""/> void main(out goo) { } }"; await VerifyKeywordAsync(text); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterReturn(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"return $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInFor(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterVar(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInUsing(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() => await VerifyKeywordAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() => await VerifyKeywordAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() => await VerifyKeywordAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic_InClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { await VerifyKeywordAsync( @"readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInReadonlyStruct() { await VerifyKeywordAsync( @"readonly $$ struct { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInReadonlyStruct_AfterReadonly() { await VerifyKeywordAsync( @"$$ readonly struct { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TestAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInClass() { await VerifyKeywordAsync( @"class C { new $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInStruct() { await VerifyKeywordAsync( @"struct S { new $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowMethod() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowProperty() { await VerifyKeywordAsync( @" class C { ref int Goo() => $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowIndexer() { await VerifyKeywordAsync( @" class C { ref int Goo => $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLocalArrowMethod(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" ref int Goo() => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInArrowLambda(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" D1 lambda = () => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(21889, "https://github.com/dotnet/roslyn/issues/21889")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] public async Task TestInConditionalExpressionTrueBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) { await VerifyWorkerAsync( AddInsideMethod(@" ref int x = ref true ? $$", topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); } [WorkItem(21889, "https://github.com/dotnet/roslyn/issues/21889")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] public async Task TestInConditionalExpressionFalseBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) { await VerifyWorkerAsync( AddInsideMethod(@" int x = 0; ref int y = ref true ? ref x : $$", topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); } [WorkItem(22253, "https://github.com/dotnet/roslyn/issues/22253")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLocalMethod(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" void Goo(int test, $$) ", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefInFor(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefForeachVariable(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefExpressionInAssignment(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" int x = 0; ref int y = ref x; y = $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefExpressionAfterReturn(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" ref int x = ref (new int[1])[0]; return ref (x = $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter() { await VerifyKeywordAsync( @"static class Extensions { static void Extension($$"); } [WorkItem(30339, "https://github.com/dotnet/roslyn/issues/30339")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword() { await VerifyKeywordAsync( @"static class Extensions { static void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter() { await VerifyKeywordAsync( @"static class Extensions { static void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword() { await VerifyAbsenceAsync( @"static class Extensions { static void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_NonStaticClass() { await VerifyKeywordAsync( @"class Extensions { static void Extension($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() { await VerifyAbsenceAsync( @"class Extensions { static void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_NonStaticClass() { await VerifyKeywordAsync( @"class Extensions { static void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() { await VerifyAbsenceAsync( @"class Extensions { static void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_NonStaticMethod() { await VerifyKeywordAsync( @"static class Extensions { void Extension($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() { await VerifyAbsenceAsync( @"static class Extensions { void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_NonStaticMethod() { await VerifyKeywordAsync( @"static class Extensions { void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() { await VerifyAbsenceAsync( @"static class Extensions { void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeNoExistingModifiers() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("in")] [InlineData("out")] [InlineData("ref")] [InlineData("ref readonly")] public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) { await VerifyAbsenceAsync($@" class C {{ delegate*<{modifier} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RefKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() { await VerifyKeywordAsync( @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement() { await VerifyKeywordAsync( @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration() { await VerifyKeywordAsync( @"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 TestNotAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterIn() { await VerifyAbsenceAsync( @"interface IGoo<in $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"interface IGoo<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInterfaceTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"interface IGoo<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAngle() { await VerifyAbsenceAsync( @"delegate void D<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterComma() { await VerifyAbsenceAsync( @"delegate void D<Goo, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestDelegateTypeVarianceNotAfterAttribute() { await VerifyAbsenceAsync( @"delegate void D<[Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotRefBaseListAfterAngle() { await VerifyAbsenceAsync( @"interface IGoo : Bar<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGenericMethod() { await VerifyAbsenceAsync( @"interface IGoo { void Goo<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRef() { await VerifyAbsenceAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOut() { await VerifyAbsenceAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThisConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C():this($$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThisConstructorInitializerNamedArgument() { await VerifyKeywordAsync( @"class C { public C():this(Goo:$$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBaseConstructorInitializer() { await VerifyKeywordAsync( @"class C { public C():base($$"); } [WorkItem(933972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/933972")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBaseConstructorInitializerNamedArgument() { await VerifyKeywordAsync( @"class C { public C():base(5, Goo:$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOperator() { await VerifyAbsenceAsync( @"class C { static int operator +($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDestructor() { await VerifyAbsenceAsync( @"class C { ~C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIndexer() { await VerifyAbsenceAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterOpenParen() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRefParam() { await VerifyAbsenceAsync( @"class C { void Goo() { new Bar(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterOutParam() { await VerifyAbsenceAsync( @"class C { void Goo() { new Bar(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterComma() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterSecondComma() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz, quux, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInObjectCreationAfterSecondNamedParam() { await VerifyKeywordAsync( @"class C { void Goo() { new Bar(baz: 4, quux: $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationExpression() { await VerifyKeywordAsync( @"class C { void Goo() { Bar($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterComma() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterSecondComma() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz, quux, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInInvocationAfterSecondNamedParam() { await VerifyKeywordAsync( @"class C { void Goo() { Bar(baz: 4, quux: $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = (ref int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLambdaDeclaration3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInDelegateDeclaration3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"var q = delegate (int a, $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefParameterList() { var text = @"Class c { /// <see cref=""main($$""/> void main(out goo) { } }"; await VerifyKeywordAsync(text); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestEmptyStatement(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"$$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestAfterReturn(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"return $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInFor(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"for (var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor2(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInFor3(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"for ($$;;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterVar(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInUsing(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"using ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() => await VerifyKeywordAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() => await VerifyKeywordAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() => await VerifyKeywordAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() => await VerifyKeywordAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() => await VerifyKeywordAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() => await VerifyKeywordAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic_InClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() => await VerifyKeywordAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { await VerifyKeywordAsync( @"readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInReadonlyStruct() { await VerifyKeywordAsync( @"readonly $$ struct { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInReadonlyStruct_AfterReadonly() { await VerifyKeywordAsync( @"$$ readonly struct { }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TestAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInClass() { await VerifyKeywordAsync( @"class C { new $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInStruct() { await VerifyKeywordAsync( @"struct S { new $$ }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowMethod() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowProperty() { await VerifyKeywordAsync( @" class C { ref int Goo() => $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInMemberArrowIndexer() { await VerifyKeywordAsync( @" class C { ref int Goo => $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLocalArrowMethod(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" ref int Goo() => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInArrowLambda(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" D1 lambda = () => $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(21889, "https://github.com/dotnet/roslyn/issues/21889")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] public async Task TestInConditionalExpressionTrueBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) { await VerifyWorkerAsync( AddInsideMethod(@" ref int x = ref true ? $$", topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); } [WorkItem(21889, "https://github.com/dotnet/roslyn/issues/21889")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData(SourceCodeKind.Regular, true)] [InlineData(SourceCodeKind.Regular, false)] [InlineData(SourceCodeKind.Script, true, Skip = "https://github.com/dotnet/roslyn/issues/44630")] [InlineData(SourceCodeKind.Script, false)] public async Task TestInConditionalExpressionFalseBranch(SourceCodeKind sourceCodeKind, bool topLevelStatement) { await VerifyWorkerAsync( AddInsideMethod(@" int x = 0; ref int y = ref true ? ref x : $$", topLevelStatement: topLevelStatement), absent: false, options: sourceCodeKind == SourceCodeKind.Script ? Options.Script : CSharp9ParseOptions); } [WorkItem(22253, "https://github.com/dotnet/roslyn/issues/22253")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInLocalMethod(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @" void Goo(int test, $$) ", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefInFor(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" for ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefForeachVariable(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" foreach ($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefExpressionInAssignment(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" int x = 0; ref int y = ref x; y = $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestRefExpressionAfterReturn(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod(@" ref int x = ref (new int[1])[0]; return ref (x = $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter() { await VerifyKeywordAsync( @"static class Extensions { static void Extension($$"); } [WorkItem(30339, "https://github.com/dotnet/roslyn/issues/30339")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword() { await VerifyKeywordAsync( @"static class Extensions { static void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter() { await VerifyKeywordAsync( @"static class Extensions { static void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword() { await VerifyAbsenceAsync( @"static class Extensions { static void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_NonStaticClass() { await VerifyKeywordAsync( @"class Extensions { static void Extension($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticClass() { await VerifyAbsenceAsync( @"class Extensions { static void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_NonStaticClass() { await VerifyKeywordAsync( @"class Extensions { static void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticClass() { await VerifyAbsenceAsync( @"class Extensions { static void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_NonStaticMethod() { await VerifyKeywordAsync( @"static class Extensions { void Extension($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_FirstParameter_AfterThisKeyword_NonStaticMethod() { await VerifyAbsenceAsync( @"static class Extensions { void Extension(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_NonStaticMethod() { await VerifyKeywordAsync( @"static class Extensions { void Extension(this int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestExtensionMethods_SecondParameter_AfterThisKeyword_NonStaticMethod() { await VerifyAbsenceAsync( @"static class Extensions { void Extension(this int i, this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeNoExistingModifiers() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("in")] [InlineData("out")] [InlineData("ref")] [InlineData("ref readonly")] public async Task TestNotInFunctionPointerTypeExistingModifiers(string modifier) { await VerifyAbsenceAsync($@" class C {{ delegate*<{modifier} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/ExternalAccess/Watch/Api/WatchHotReloadService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Watch.Api { internal sealed class WatchHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) => _capabilities = capabilities; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedTypes; public Update(Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; private readonly ImmutableArray<string> _capabilities; public WatchHotReloadService(HostWorkspaceServices services, ImmutableArray<string> capabilities) => (_encService, _capabilities) = (services.GetRequiredService<IEditAndContinueWorkspaceService>(), capabilities); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(_capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call or /// the one passed to <see cref="StartSessionAsync(Solution, CancellationToken)"/> for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService.EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { _encService.CommitSolutionUpdate(sessionId, out _); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update(update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly WatchHotReloadService _instance; internal TestAccessor(WatchHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.Watch.Api { internal sealed class WatchHotReloadService { private sealed class DebuggerService : IManagedEditAndContinueDebuggerService { private readonly ImmutableArray<string> _capabilities; public DebuggerService(ImmutableArray<string> capabilities) => _capabilities = capabilities; public Task<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(CancellationToken cancellationToken) => Task.FromResult(ImmutableArray<ManagedActiveStatementDebugInfo>.Empty); public Task<ManagedEditAndContinueAvailability> GetAvailabilityAsync(Guid module, CancellationToken cancellationToken) => Task.FromResult(new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Available)); public Task<ImmutableArray<string>> GetCapabilitiesAsync(CancellationToken cancellationToken) => Task.FromResult(_capabilities); public Task PrepareModuleForUpdateAsync(Guid module, CancellationToken cancellationToken) => Task.CompletedTask; } public readonly struct Update { public readonly Guid ModuleId; public readonly ImmutableArray<byte> ILDelta; public readonly ImmutableArray<byte> MetadataDelta; public readonly ImmutableArray<byte> PdbDelta; public readonly ImmutableArray<int> UpdatedTypes; public Update(Guid moduleId, ImmutableArray<byte> ilDelta, ImmutableArray<byte> metadataDelta, ImmutableArray<byte> pdbDelta, ImmutableArray<int> updatedTypes) { ModuleId = moduleId; ILDelta = ilDelta; MetadataDelta = metadataDelta; PdbDelta = pdbDelta; UpdatedTypes = updatedTypes; } } private static readonly ActiveStatementSpanProvider s_solutionActiveStatementSpanProvider = (_, _, _) => ValueTaskFactory.FromResult(ImmutableArray<ActiveStatementSpan>.Empty); private readonly IEditAndContinueWorkspaceService _encService; private DebuggingSessionId _sessionId; private readonly ImmutableArray<string> _capabilities; public WatchHotReloadService(HostWorkspaceServices services, ImmutableArray<string> capabilities) => (_encService, _capabilities) = (services.GetRequiredService<IEditAndContinueWorkspaceService>(), capabilities); /// <summary> /// Starts the watcher. /// </summary> /// <param name="solution">Solution that represents sources that match the built binaries on disk.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task StartSessionAsync(Solution solution, CancellationToken cancellationToken) { var newSessionId = await _encService.StartDebuggingSessionAsync( solution, new DebuggerService(_capabilities), captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: false, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(_sessionId == default, "Session already started"); _sessionId = newSessionId; } /// <summary> /// Emits updates for all projects that differ between the given <paramref name="solution"/> snapshot and the one given to the previous successful call or /// the one passed to <see cref="StartSessionAsync(Solution, CancellationToken)"/> for the first invocation. /// </summary> /// <param name="solution">Solution snapshot.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// Updates (one for each changed project) and Rude Edit diagnostics. Does not include syntax or semantic diagnostics. /// </returns> public async Task<(ImmutableArray<Update> updates, ImmutableArray<Diagnostic> diagnostics)> EmitSolutionUpdateAsync(Solution solution, CancellationToken cancellationToken) { var sessionId = _sessionId; Contract.ThrowIfFalse(sessionId != default, "Session has not started"); var results = await _encService.EmitSolutionUpdateAsync(sessionId, solution, s_solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (results.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { _encService.CommitSolutionUpdate(sessionId, out _); } var updates = results.ModuleUpdates.Updates.SelectAsArray( update => new Update(update.Module, update.ILDelta, update.MetadataDelta, update.PdbDelta, update.UpdatedTypes)); var diagnostics = await results.GetAllDiagnosticsAsync(solution, cancellationToken).ConfigureAwait(false); return (updates, diagnostics); } public void EndSession() { Contract.ThrowIfFalse(_sessionId != default, "Session has not started"); _encService.EndDebuggingSession(_sessionId, out _); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly WatchHotReloadService _instance; internal TestAccessor(WatchHotReloadService instance) => _instance = instance; public DebuggingSessionId SessionId => _instance._sessionId; } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/CodeFixes/RemoveUnusedMembers/AbstractRemoveUnusedMembersCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnusedMembers { internal abstract class AbstractRemoveUnusedMembersCodeFixProvider<TFieldDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider where TFieldDeclarationSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnusedMembersDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; /// <summary> /// This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators /// within a field declaration should be removed, /// i.e. if all the fields declared within a field declaration are unused, /// we can remove the entire field declaration instead of individual variable declarators. /// </summary> protected abstract void AdjustAndAddAppropriateDeclaratorsToRemove(HashSet<TFieldDeclarationSyntax> fieldDeclarators, HashSet<SyntaxNode> declarators); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var declarators = new HashSet<SyntaxNode>(); var fieldDeclarators = new HashSet<TFieldDeclarationSyntax>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declarationService = document.GetLanguageService<ISymbolDeclarationService>(); // Compute declarators to remove, and also track common field declarators. foreach (var diagnostic in diagnostics) { // Get symbol to be removed. var diagnosticNode = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); var symbol = semanticModel.GetDeclaredSymbol(diagnosticNode, cancellationToken); Debug.Assert(symbol != null); // Get symbol declarations to be removed. foreach (var declReference in declarationService.GetDeclarations(symbol)) { var node = await declReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); declarators.Add(node); // For fields, the declaration node is the variable declarator. // We also track the ancestor FieldDeclarationSyntax which may declare more then one field. if (symbol.Kind == SymbolKind.Field) { var fieldDeclarator = node.FirstAncestorOrSelf<TFieldDeclarationSyntax>(); fieldDeclarators.Add(fieldDeclarator); } } } // If all the fields declared within a field declaration are unused, // we can remove the entire field declaration instead of individual variable declarators. if (fieldDeclarators.Count > 0) { AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators, declarators); } // Remove all the symbol declarator nodes. foreach (var declarator in declarators) { editor.RemoveNode(declarator); } } /// <summary> /// If all the <paramref name="childDeclarators"/> are contained in <paramref name="declarators"/>, /// the removes the <paramref name="childDeclarators"/> from <paramref name="declarators"/>, and /// adds the <paramref name="parentDeclaration"/> to the <paramref name="declarators"/>. /// </summary> protected static void AdjustAndAddAppropriateDeclaratorsToRemove(SyntaxNode parentDeclaration, IEnumerable<SyntaxNode> childDeclarators, HashSet<SyntaxNode> declarators) { if (declarators.Contains(parentDeclaration)) { Debug.Assert(childDeclarators.All(c => !declarators.Contains(c))); return; } var declaratorsContainsAllChildren = true; foreach (var childDeclarator in childDeclarators) { if (!declarators.Contains(childDeclarator)) { declaratorsContainsAllChildren = false; break; } } if (declaratorsContainsAllChildren) { // Remove the entire parent declaration instead of individual child declarators within it. declarators.Add(parentDeclaration); declarators.RemoveAll(childDeclarators); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unused_member, createChangedDocument, nameof(AnalyzersResources.Remove_unused_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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnusedMembers { internal abstract class AbstractRemoveUnusedMembersCodeFixProvider<TFieldDeclarationSyntax> : SyntaxEditorBasedCodeFixProvider where TFieldDeclarationSyntax : SyntaxNode { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveUnusedMembersDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; /// <summary> /// This method adjusts the <paramref name="declarators"/> to remove based on whether or not all variable declarators /// within a field declaration should be removed, /// i.e. if all the fields declared within a field declaration are unused, /// we can remove the entire field declaration instead of individual variable declarators. /// </summary> protected abstract void AdjustAndAddAppropriateDeclaratorsToRemove(HashSet<TFieldDeclarationSyntax> fieldDeclarators, HashSet<SyntaxNode> declarators); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var declarators = new HashSet<SyntaxNode>(); var fieldDeclarators = new HashSet<TFieldDeclarationSyntax>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var declarationService = document.GetLanguageService<ISymbolDeclarationService>(); // Compute declarators to remove, and also track common field declarators. foreach (var diagnostic in diagnostics) { // Get symbol to be removed. var diagnosticNode = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); var symbol = semanticModel.GetDeclaredSymbol(diagnosticNode, cancellationToken); Debug.Assert(symbol != null); // Get symbol declarations to be removed. foreach (var declReference in declarationService.GetDeclarations(symbol)) { var node = await declReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); declarators.Add(node); // For fields, the declaration node is the variable declarator. // We also track the ancestor FieldDeclarationSyntax which may declare more then one field. if (symbol.Kind == SymbolKind.Field) { var fieldDeclarator = node.FirstAncestorOrSelf<TFieldDeclarationSyntax>(); fieldDeclarators.Add(fieldDeclarator); } } } // If all the fields declared within a field declaration are unused, // we can remove the entire field declaration instead of individual variable declarators. if (fieldDeclarators.Count > 0) { AdjustAndAddAppropriateDeclaratorsToRemove(fieldDeclarators, declarators); } // Remove all the symbol declarator nodes. foreach (var declarator in declarators) { editor.RemoveNode(declarator); } } /// <summary> /// If all the <paramref name="childDeclarators"/> are contained in <paramref name="declarators"/>, /// the removes the <paramref name="childDeclarators"/> from <paramref name="declarators"/>, and /// adds the <paramref name="parentDeclaration"/> to the <paramref name="declarators"/>. /// </summary> protected static void AdjustAndAddAppropriateDeclaratorsToRemove(SyntaxNode parentDeclaration, IEnumerable<SyntaxNode> childDeclarators, HashSet<SyntaxNode> declarators) { if (declarators.Contains(parentDeclaration)) { Debug.Assert(childDeclarators.All(c => !declarators.Contains(c))); return; } var declaratorsContainsAllChildren = true; foreach (var childDeclarator in childDeclarators) { if (!declarators.Contains(childDeclarator)) { declaratorsContainsAllChildren = false; break; } } if (declaratorsContainsAllChildren) { // Remove the entire parent declaration instead of individual child declarators within it. declarators.Add(parentDeclaration); declarators.RemoveAll(childDeclarators); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(AnalyzersResources.Remove_unused_member, createChangedDocument, nameof(AnalyzersResources.Remove_unused_member)) { } } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Parser/DocumentationCommentParser.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; // TODO: The Xml parser recognizes most commonplace XML, according to the XML spec. // It does not recognize the following: // // * Document Type Definition // <!DOCTYPE ... > // * Element Type Declaration, Attribute-List Declarations, Entity Declarations, Notation Declarations // <!ELEMENT ... > // <!ATTLIST ... > // <!ENTITY ... > // <!NOTATION ... > // * Conditional Sections // <![INCLUDE[ ... ]]> // <![IGNORE[ ... ]]> // // This probably does not matter. However, if it becomes necessary to recognize any // of these bits of XML, the most sensible thing to do is probably to scan them without // trying to understand them, e.g. like comments or CDATA, so that they are available // to whoever processes these comments and do not produce an error. internal class DocumentationCommentParser : SyntaxParser { private readonly SyntaxListPool _pool = new SyntaxListPool(); private bool _isDelimited; internal DocumentationCommentParser(Lexer lexer, LexerMode modeflags) : base(lexer, LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags, null, null, true) { _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; } internal void ReInitialize(LexerMode modeflags) { base.ReInitialize(); this.Mode = LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags; _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; } private LexerMode SetMode(LexerMode mode) { var tmp = this.Mode; this.Mode = mode | (tmp & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle)); return tmp; } private void ResetMode(LexerMode mode) { this.Mode = mode; } public DocumentationCommentTriviaSyntax ParseDocumentationComment(out bool isTerminated) { var nodes = _pool.Allocate<XmlNodeSyntax>(); try { this.ParseXmlNodes(nodes); // It's possible that we finish parsing the xml, and we are still left in the middle // of an Xml comment. For example, // // /// <goo></goo></uhoh> // ^ // In this case, we stop at the caret. We need to ensure that we consume the remainder // of the doc comment here, since otherwise we will return the lexer to the state // where it recognizes C# tokens, which means that C# parser will get the </uhoh>, // which is not at all what we want. if (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) { this.ParseRemainder(nodes); } var eoc = this.EatToken(SyntaxKind.EndOfDocumentationCommentToken); isTerminated = !_isDelimited || (eoc.LeadingTrivia.Count > 0 && eoc.LeadingTrivia[eoc.LeadingTrivia.Count - 1].ToString() == "*/"); SyntaxKind kind = _isDelimited ? SyntaxKind.MultiLineDocumentationCommentTrivia : SyntaxKind.SingleLineDocumentationCommentTrivia; return SyntaxFactory.DocumentationCommentTrivia(kind, nodes.ToList(), eoc); } finally { _pool.Free(nodes); } } public void ParseRemainder(SyntaxListBuilder<XmlNodeSyntax> nodes) { bool endTag = this.CurrentToken.Kind == SyntaxKind.LessThanSlashToken; var saveMode = this.SetMode(LexerMode.XmlCDataSectionText); var textTokens = _pool.Allocate(); try { while (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) { var token = this.EatToken(); // TODO: It is possible that a non-literal gets in here. ]]>, specifically. Is that ok? textTokens.Add(token); } var allRemainderText = SyntaxFactory.XmlText(textTokens.ToList()); XmlParseErrorCode code = endTag ? XmlParseErrorCode.XML_EndTagNotExpected : XmlParseErrorCode.XML_ExpectedEndOfXml; allRemainderText = WithAdditionalDiagnostics(allRemainderText, new XmlSyntaxDiagnosticInfo(0, 1, code)); nodes.Add(allRemainderText); } finally { _pool.Free(textTokens); } this.ResetMode(saveMode); } private void ParseXmlNodes(SyntaxListBuilder<XmlNodeSyntax> nodes) { while (true) { var node = this.ParseXmlNode(); if (node == null) { return; } nodes.Add(node); } } private XmlNodeSyntax ParseXmlNode() { switch (this.CurrentToken.Kind) { case SyntaxKind.XmlTextLiteralToken: case SyntaxKind.XmlTextLiteralNewLineToken: case SyntaxKind.XmlEntityLiteralToken: return this.ParseXmlText(); case SyntaxKind.LessThanToken: return this.ParseXmlElement(); case SyntaxKind.XmlCommentStartToken: return this.ParseXmlComment(); case SyntaxKind.XmlCDataStartToken: return this.ParseXmlCDataSection(); case SyntaxKind.XmlProcessingInstructionStartToken: return this.ParseXmlProcessingInstruction(); case SyntaxKind.EndOfDocumentationCommentToken: return null; default: // This means we have some unrecognized token. We probably need to give an error. return null; } } private bool IsXmlNodeStartOrStop() { switch (this.CurrentToken.Kind) { case SyntaxKind.LessThanToken: case SyntaxKind.LessThanSlashToken: case SyntaxKind.XmlCommentStartToken: case SyntaxKind.XmlCDataStartToken: case SyntaxKind.XmlProcessingInstructionStartToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.SlashGreaterThanToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; default: return false; } } private XmlNodeSyntax ParseXmlText() { var textTokens = _pool.Allocate(); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken) { textTokens.Add(this.EatToken()); } var list = textTokens.ToList(); _pool.Free(textTokens); return SyntaxFactory.XmlText(list); } private XmlNodeSyntax ParseXmlElement() { var lessThan = this.EatToken(SyntaxKind.LessThanToken); // guaranteed var saveMode = this.SetMode(LexerMode.XmlElementTag); var name = this.ParseXmlName(); if (lessThan.GetTrailingTriviaWidth() > 0 || name.GetLeadingTriviaWidth() > 0) { // The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>' name = this.WithXmlParseError(name, XmlParseErrorCode.XML_InvalidWhitespace); } var attrs = _pool.Allocate<XmlAttributeSyntax>(); try { this.ParseXmlAttributes(ref name, attrs); if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { var startTag = SyntaxFactory.XmlElementStartTag(lessThan, name, attrs, this.EatToken()); this.SetMode(LexerMode.XmlDocComment); var nodes = _pool.Allocate<XmlNodeSyntax>(); try { this.ParseXmlNodes(nodes); XmlNameSyntax endName; SyntaxToken greaterThan; // end tag var lessThanSlash = this.EatToken(SyntaxKind.LessThanSlashToken, reportError: false); // If we didn't see "</", then we can't really be confident that this is actually an end tag, // so just insert a missing one. if (lessThanSlash.IsMissing) { this.ResetMode(saveMode); lessThanSlash = this.WithXmlParseError(lessThanSlash, XmlParseErrorCode.XML_EndTagExpected, name.ToString()); endName = SyntaxFactory.XmlName(prefix: null, localName: SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); greaterThan = SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken); } else { this.SetMode(LexerMode.XmlElementTag); endName = this.ParseXmlName(); if (lessThanSlash.GetTrailingTriviaWidth() > 0 || endName.GetLeadingTriviaWidth() > 0) { // The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>' endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_InvalidWhitespace); } if (!endName.IsMissing && !MatchingXmlNames(name, endName)) { endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_ElementTypeMatch, endName.ToString(), name.ToString()); } // if we don't see the greater than token then skip the badness until we do or abort if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) { this.SkipBadTokens(ref endName, null, p => p.CurrentToken.Kind != SyntaxKind.GreaterThanToken, p => p.IsXmlNodeStartOrStop(), XmlParseErrorCode.XML_InvalidToken ); } greaterThan = this.EatToken(SyntaxKind.GreaterThanToken); } var endTag = SyntaxFactory.XmlElementEndTag(lessThanSlash, endName, greaterThan); this.ResetMode(saveMode); return SyntaxFactory.XmlElement(startTag, nodes.ToList(), endTag); } finally { _pool.Free(nodes); } } else { var slashGreater = this.EatToken(SyntaxKind.SlashGreaterThanToken, false); if (slashGreater.IsMissing && !name.IsMissing) { slashGreater = this.WithXmlParseError(slashGreater, XmlParseErrorCode.XML_ExpectedEndOfTag, name.ToString()); } this.ResetMode(saveMode); return SyntaxFactory.XmlEmptyElement(lessThan, name, attrs, slashGreater); } } finally { _pool.Free(attrs); } } private static bool MatchingXmlNames(XmlNameSyntax name, XmlNameSyntax endName) { // PERF: because of deduplication we often get the same name for name and endName, // so we will check for such case first before materializing text for entire nodes // and comparing that. if (name == endName) { return true; } // before doing ToString, check if // all nodes contributing to ToString are recursively the same // NOTE: leading and trailing trivia do not contribute to ToString if (!name.HasLeadingTrivia && !endName.HasTrailingTrivia && name.IsEquivalentTo(endName)) { return true; } return name.ToString() == endName.ToString(); } // assuming this is not used concurrently private readonly HashSet<string> _attributesSeen = new HashSet<string>(); private void ParseXmlAttributes(ref XmlNameSyntax elementName, SyntaxListBuilder<XmlAttributeSyntax> attrs) { _attributesSeen.Clear(); while (true) { if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { var attr = this.ParseXmlAttribute(elementName); string attrName = attr.Name.ToString(); if (_attributesSeen.Contains(attrName)) { attr = this.WithXmlParseError(attr, XmlParseErrorCode.XML_DuplicateAttribute, attrName); } else { _attributesSeen.Add(attrName); } attrs.Add(attr); } else { var skip = this.SkipBadTokens(ref elementName, attrs, // not expected condition p => p.CurrentToken.Kind != SyntaxKind.IdentifierName, // abort condition (looks like something we might understand later) p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.CurrentToken.Kind == SyntaxKind.SlashGreaterThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanSlashToken || p.CurrentToken.Kind == SyntaxKind.EndOfDocumentationCommentToken || p.CurrentToken.Kind == SyntaxKind.EndOfFileToken, XmlParseErrorCode.XML_InvalidToken ); if (skip == SkipResult.Abort) { break; } } } } private enum SkipResult { Continue, Abort } private SkipResult SkipBadTokens<T>( ref T startNode, SyntaxListBuilder list, Func<DocumentationCommentParser, bool> isNotExpectedFunction, Func<DocumentationCommentParser, bool> abortFunction, XmlParseErrorCode error ) where T : CSharpSyntaxNode { var badTokens = default(SyntaxListBuilder<SyntaxToken>); bool hasError = false; try { SkipResult result = SkipResult.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { result = SkipResult.Abort; break; } if (badTokens.IsNull) { badTokens = _pool.Allocate<SyntaxToken>(); } var token = this.EatToken(); if (!hasError) { token = this.WithXmlParseError(token, error, token.ToString()); hasError = true; } badTokens.Add(token); } if (!badTokens.IsNull && badTokens.Count > 0) { // use skipped text since cannot nest structured trivia under structured trivia if (list == null || list.Count == 0) { startNode = AddTrailingSkippedSyntax(startNode, badTokens.ToListNode()); } else { list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], badTokens.ToListNode()); } return result; } else { // somehow we did not consume anything, so tell caller to abort parse rule return SkipResult.Abort; } } finally { if (!badTokens.IsNull) { _pool.Free(badTokens); } } } private XmlAttributeSyntax ParseXmlAttribute(XmlNameSyntax elementName) { var attrName = this.ParseXmlName(); if (attrName.GetLeadingTriviaWidth() == 0) { // The Xml spec requires whitespace here: STag ::= '<' Name (S Attribute)* S? '>' attrName = this.WithXmlParseError(attrName, XmlParseErrorCode.XML_WhitespaceMissing); } var equals = this.EatToken(SyntaxKind.EqualsToken, false); if (equals.IsMissing) { equals = this.WithXmlParseError(equals, XmlParseErrorCode.XML_MissingEqualsAttribute); switch (this.CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: case SyntaxKind.DoubleQuoteToken: // There could be a value coming up, let's keep parsing. break; default: // This is probably not a complete attribute. return SyntaxFactory.XmlTextAttribute( attrName, equals, SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken), default(SyntaxList<SyntaxToken>), SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken)); } } SyntaxToken startQuote; SyntaxToken endQuote; string attrNameText = attrName.LocalName.ValueText; bool hasNoPrefix = attrName.Prefix == null; if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.CrefAttributeName) && !IsVerbatimCref()) { CrefSyntax cref; this.ParseCrefAttribute(out startQuote, out cref, out endQuote); return SyntaxFactory.XmlCrefAttribute(attrName, equals, startQuote, cref, endQuote); } else if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.NameAttributeName) && XmlElementSupportsNameAttribute(elementName)) { IdentifierNameSyntax identifier; this.ParseNameAttribute(out startQuote, out identifier, out endQuote); return SyntaxFactory.XmlNameAttribute(attrName, equals, startQuote, identifier, endQuote); } else { var textTokens = _pool.Allocate<SyntaxToken>(); try { this.ParseXmlAttributeText(out startQuote, textTokens, out endQuote); return SyntaxFactory.XmlTextAttribute(attrName, equals, startQuote, textTokens, endQuote); } finally { _pool.Free(textTokens); } } } private static bool XmlElementSupportsNameAttribute(XmlNameSyntax elementName) { if (elementName.Prefix != null) { return false; } string localName = elementName.LocalName.ValueText; return DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterReferenceElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterReferenceElementName); } private bool IsVerbatimCref() { // As in XMLDocWriter::ReplaceReferences, if the first character of the value is not colon and the second character // is, then don't process the cref - just emit it as-is. bool isVerbatim = false; var resetPoint = this.GetResetPoint(); SyntaxToken openQuote = EatToken(this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken); // NOTE: Don't need to save mode, since we're already using a reset point. this.SetMode(LexerMode.XmlCharacter); SyntaxToken current = this.CurrentToken; if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) && current.ValueText != SyntaxFacts.GetText(openQuote.Kind) && current.ValueText != ":") { EatToken(); current = this.CurrentToken; if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) && current.ValueText == ":") { isVerbatim = true; } } this.Reset(ref resetPoint); this.Release(ref resetPoint); return isVerbatim; } private void ParseCrefAttribute(out SyntaxToken startQuote, out CrefSyntax cref, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlCrefQuote : LexerMode.XmlCrefDoubleQuote); cref = this.ParseCrefAttributeValue(); this.ResetMode(saveMode); } endQuote = ParseXmlAttributeEndQuote(quoteKind); } private void ParseNameAttribute(out SyntaxToken startQuote, out IdentifierNameSyntax identifier, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlNameQuote : LexerMode.XmlNameDoubleQuote); identifier = this.ParseNameAttributeValue(); this.ResetMode(saveMode); } endQuote = ParseXmlAttributeEndQuote(quoteKind); } private void ParseXmlAttributeText(out SyntaxToken startQuote, SyntaxListBuilder<SyntaxToken> textTokens, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; // NOTE: Being a bit sneaky here - if the width isn't 0, we consumed something else in // place of the quote and we should continue parsing the attribute. if (startQuote.IsMissing && startQuote.FullWidth == 0) { endQuote = SyntaxFactory.MissingToken(quoteKind); } else { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlAttributeTextQuote : LexerMode.XmlAttributeTextDoubleQuote); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken || this.CurrentToken.Kind == SyntaxKind.LessThanToken) { var token = this.EatToken(); if (token.Kind == SyntaxKind.LessThanToken) { // TODO: It is possible that a non-literal gets in here. <, specifically. Is that ok? token = this.WithXmlParseError(token, XmlParseErrorCode.XML_LessThanInAttributeValue); } textTokens.Add(token); } this.ResetMode(saveMode); // NOTE: This will never consume a non-ascii quote, since non-ascii quotes // are legal in the attribute value and are consumed by the preceding loop. endQuote = ParseXmlAttributeEndQuote(quoteKind); } } private SyntaxToken ParseXmlAttributeStartQuote() { if (IsNonAsciiQuotationMark(this.CurrentToken)) { return SkipNonAsciiQuotationMark(); } var quoteKind = this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken; var startQuote = this.EatToken(quoteKind, reportError: false); if (startQuote.IsMissing) { startQuote = this.WithXmlParseError(startQuote, XmlParseErrorCode.XML_StringLiteralNoStartQuote); } return startQuote; } private SyntaxToken ParseXmlAttributeEndQuote(SyntaxKind quoteKind) { if (IsNonAsciiQuotationMark(this.CurrentToken)) { return SkipNonAsciiQuotationMark(); } var endQuote = this.EatToken(quoteKind, reportError: false); if (endQuote.IsMissing) { endQuote = this.WithXmlParseError(endQuote, XmlParseErrorCode.XML_StringLiteralNoEndQuote); } return endQuote; } private SyntaxToken SkipNonAsciiQuotationMark() { var quote = SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken); quote = AddTrailingSkippedSyntax(quote, EatToken()); quote = this.WithXmlParseError(quote, XmlParseErrorCode.XML_StringLiteralNonAsciiQuote); return quote; } /// <summary> /// These aren't acceptable in place of ASCII quotation marks in XML, /// but we want to consume them (and produce an appropriate error) if /// they occur in a place where a quotation mark is legal. /// </summary> private static bool IsNonAsciiQuotationMark(SyntaxToken token) { return token.Text.Length == 1 && SyntaxFacts.IsNonAsciiQuotationMark(token.Text[0]); } private XmlNameSyntax ParseXmlName() { var id = this.EatToken(SyntaxKind.IdentifierToken); XmlPrefixSyntax prefix = null; if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { var colon = this.EatToken(); int prefixTrailingWidth = id.GetTrailingTriviaWidth(); int colonLeadingWidth = colon.GetLeadingTriviaWidth(); if (prefixTrailingWidth > 0 || colonLeadingWidth > 0) { // NOTE: offset is relative to full-span start of colon (i.e. before leading trivia). int offset = -prefixTrailingWidth; int width = prefixTrailingWidth + colonLeadingWidth; colon = WithAdditionalDiagnostics(colon, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace)); } prefix = SyntaxFactory.XmlPrefix(id, colon); id = this.EatToken(SyntaxKind.IdentifierToken); int colonTrailingWidth = colon.GetTrailingTriviaWidth(); int localNameLeadingWidth = id.GetLeadingTriviaWidth(); if (colonTrailingWidth > 0 || localNameLeadingWidth > 0) { // NOTE: offset is relative to full-span start of identifier (i.e. before leading trivia). int offset = -colonTrailingWidth; int width = colonTrailingWidth + localNameLeadingWidth; id = WithAdditionalDiagnostics(id, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace)); // CONSIDER: Another interpretation would be that the local part of this name is a missing identifier and the identifier // we've just consumed is actually part of something else (e.g. an attribute name). } } return SyntaxFactory.XmlName(prefix, id); } private XmlCommentSyntax ParseXmlComment() { var lessThanExclamationMinusMinusToken = this.EatToken(SyntaxKind.XmlCommentStartToken); var saveMode = this.SetMode(LexerMode.XmlCommentText); var textTokens = _pool.Allocate<SyntaxToken>(); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.MinusMinusToken) { var token = this.EatToken(); if (token.Kind == SyntaxKind.MinusMinusToken) { // TODO: It is possible that a non-literal gets in here. --, specifically. Is that ok? token = this.WithXmlParseError(token, XmlParseErrorCode.XML_IncorrectComment); } textTokens.Add(token); } var list = textTokens.ToList(); _pool.Free(textTokens); var minusMinusGreaterThanToken = this.EatToken(SyntaxKind.XmlCommentEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, list, minusMinusGreaterThanToken); } private XmlCDataSectionSyntax ParseXmlCDataSection() { var startCDataToken = this.EatToken(SyntaxKind.XmlCDataStartToken); var saveMode = this.SetMode(LexerMode.XmlCDataSectionText); var textTokens = new SyntaxListBuilder<SyntaxToken>(10); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) { textTokens.Add(this.EatToken()); } var endCDataToken = this.EatToken(SyntaxKind.XmlCDataEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); } private XmlProcessingInstructionSyntax ParseXmlProcessingInstruction() { var startProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionStartToken); var saveMode = this.SetMode(LexerMode.XmlElementTag); //this mode accepts names var name = this.ParseXmlName(); // NOTE: The XML spec says that name cannot be "xml" (case-insensitive comparison), // but Dev10 does not enforce this. this.SetMode(LexerMode.XmlProcessingInstructionText); //this mode consumes text var textTokens = new SyntaxListBuilder<SyntaxToken>(10); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) { var textToken = this.EatToken(); // NOTE: The XML spec says that the each text token must begin with a whitespace // character, but Dev10 does not enforce this. textTokens.Add(textToken); } var endProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); } protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int length) { // NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride. if (InCref) { SyntaxDiagnosticInfo rawInfo = base.GetExpectedTokenError(expected, actual, offset, length); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(rawInfo.Offset, rawInfo.Width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); return crefInfo; } switch (expected) { case SyntaxKind.IdentifierToken: return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_ExpectedIdentifier); default: return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); } } protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) { // NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride. if (InCref) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); return GetExpectedTokenError(expected, actual, offset, width); } switch (expected) { case SyntaxKind.IdentifierToken: return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_ExpectedIdentifier); default: return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); } } private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code)); } private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code, params string[] args) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args)); } private SyntaxToken WithXmlParseError(SyntaxToken node, XmlParseErrorCode code, params string[] args) { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args)); } protected override TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) { // Don't attach any diagnostics to syntax nodes within a documentation comment if the DocumentationMode // is not at least Diagnose. return Options.DocumentationMode >= DocumentationMode.Diagnose ? base.WithAdditionalDiagnostics<TNode>(node, diagnostics) : node; } #region Cref /// <summary> /// ACASEY: This grammar is derived from the behavior and sources of the native compiler. /// Tokens start with underscores (I've cheated for _PredefinedTypeToken, which is not actually a /// SyntaxKind), "*" indicates "0 or more", "?" indicates "0 or 1", and parentheses are for grouping. /// /// Cref = CrefType _DotToken CrefMember /// | CrefType /// | CrefMember /// | CrefFirstType _OpenParenToken CrefParameterList? _CloseParenToken /// CrefName = _IdentifierToken (_LessThanToken _IdentifierToken (_CommaToken _IdentifierToken)* _GreaterThanToken)? /// CrefFirstType = ((_IdentifierToken _ColonColonToken)? CrefName) /// | _PredefinedTypeToken /// CrefType = CrefFirstType (_DotToken CrefName)* /// CrefMember = CrefName (_OpenParenToken CrefParameterList? _CloseParenToken)? /// | _ThisKeyword (_OpenBracketToken CrefParameterList _CloseBracketToken)? /// | _OperatorKeyword _OperatorToken (_OpenParenToken CrefParameterList? _CloseParenToken)? /// | (_ImplicitKeyword | _ExplicitKeyword) _OperatorKeyword CrefParameterType (_OpenParenToken CrefParameterList? _CloseParenToken)? /// CrefParameterList = CrefParameter (_CommaToken CrefParameter)* /// CrefParameter = (_RefKeyword | _OutKeyword)? CrefParameterType /// CrefParameterType = CrefParameterType2 _QuestionToken? _AsteriskToken* (_OpenBracketToken _CommaToken* _CloseBracketToken)* /// CrefParameterType2 = (((_IdentifierToken _ColonColonToken)? CrefParameterType3) | _PredefinedTypeToken) (_DotToken CrefParameterType3)* /// CrefParameterType3 = _IdentifierToken (_LessThanToken CrefParameterType (_CommaToken CrefParameterType)* _GreaterThanToken)? /// /// NOTE: type parameters, not type arguments /// NOTE: the first production of Cref is preferred to the other two /// NOTE: pointer, array, and nullable types only work in parameters /// NOTE: CrefParameterType2 and CrefParameterType3 correspond to CrefType and CrefName, respectively. /// Since the only difference is that they accept non-identifier type arguments, this is accomplished /// using parameters on the parsing methods (rather than whole new methods). /// </summary> private CrefSyntax ParseCrefAttributeValue() { CrefSyntax result; TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: true, checkForMember: true); if (type == null) { result = ParseMemberCref(); } else if (IsEndOfCrefAttribute) { result = SyntaxFactory.TypeCref(type); } else if (type.Kind != SyntaxKind.QualifiedName && this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // Special case for crefs like "string()" and "A::B()". CrefParameterListSyntax parameters = ParseCrefParameterList(); result = SyntaxFactory.NameMemberCref(type, parameters); } else { SyntaxToken dot = EatToken(SyntaxKind.DotToken); MemberCrefSyntax member = ParseMemberCref(); result = SyntaxFactory.QualifiedCref(type, dot, member); } bool needOverallError = !IsEndOfCrefAttribute || result.ContainsDiagnostics; if (!IsEndOfCrefAttribute) { var badTokens = _pool.Allocate<SyntaxToken>(); while (!IsEndOfCrefAttribute) { badTokens.Add(this.EatToken()); } result = AddTrailingSkippedSyntax(result, badTokens.ToListNode()); _pool.Free(badTokens); } if (needOverallError) { result = this.AddError(result, ErrorCode.WRN_BadXMLRefSyntax, result.ToFullString()); } return result; } /// <summary> /// Parse the custom cref syntax for a named member (method, property, etc), /// an indexer, an overloadable operator, or a user-defined conversion. /// </summary> private MemberCrefSyntax ParseMemberCref() { switch (CurrentToken.Kind) { case SyntaxKind.ThisKeyword: return ParseIndexerMemberCref(); case SyntaxKind.OperatorKeyword: return ParseOperatorMemberCref(); case SyntaxKind.ExplicitKeyword: case SyntaxKind.ImplicitKeyword: return ParseConversionOperatorMemberCref(); default: return ParseNameMemberCref(); } } /// <summary> /// Parse a named member (method, property, etc), with optional type /// parameters and regular parameters. /// </summary> private NameMemberCrefSyntax ParseNameMemberCref() { SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers: true); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.NameMemberCref(name, parameters); } /// <summary> /// Parse an indexer member, with optional parameters. /// </summary> private IndexerMemberCrefSyntax ParseIndexerMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.ThisKeyword); SyntaxToken thisKeyword = EatToken(); CrefBracketedParameterListSyntax parameters = ParseBracketedCrefParameterList(); return SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); } /// <summary> /// Parse an overloadable operator, with optional parameters. /// </summary> private OperatorMemberCrefSyntax ParseOperatorMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.OperatorKeyword); SyntaxToken operatorKeyword = EatToken(); SyntaxToken operatorToken; if (SyntaxFacts.IsAnyOverloadableOperator(CurrentToken.Kind)) { operatorToken = EatToken(); } else { operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); // Grab the offset and width before we consume the invalid keyword and change our position. int offset; int width; GetDiagnosticSpanForMissingToken(out offset, out width); if (SyntaxFacts.IsUnaryOperatorDeclarationToken(CurrentToken.Kind) || SyntaxFacts.IsBinaryExpressionOperatorToken(CurrentToken.Kind)) { operatorToken = AddTrailingSkippedSyntax(operatorToken, EatToken()); } SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo); } // Have to fake >> because it looks like the closing of nested type parameter lists (e.g. A<A<T>>). // Have to fake >= so the lexer doesn't mishandle >>=. if (operatorToken.Kind == SyntaxKind.GreaterThanToken && operatorToken.GetTrailingTriviaWidth() == 0 && CurrentToken.GetLeadingTriviaWidth() == 0) { if (CurrentToken.Kind == SyntaxKind.GreaterThanToken) { var operatorToken2 = this.EatToken(); operatorToken = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); } else if (CurrentToken.Kind == SyntaxKind.EqualsToken) { var operatorToken2 = this.EatToken(); operatorToken = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanEqualsToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); } else if (CurrentToken.Kind == SyntaxKind.GreaterThanEqualsToken) { var operatorToken2 = this.EatToken(); var nonOverloadableOperator = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanEqualsToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); // Add non-overloadable operator as skipped token. operatorToken = AddTrailingSkippedSyntax(operatorToken, nonOverloadableOperator); // Add an appropriate diagnostic. const int offset = 0; int width = nonOverloadableOperator.Width; SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo); } } Debug.Assert(SyntaxFacts.IsAnyOverloadableOperator(operatorToken.Kind)); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters); } /// <summary> /// Parse a user-defined conversion, with optional parameters. /// </summary> private ConversionOperatorMemberCrefSyntax ParseConversionOperatorMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.ExplicitKeyword || CurrentToken.Kind == SyntaxKind.ImplicitKeyword); SyntaxToken implicitOrExplicit = EatToken(); SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicit, operatorKeyword, type, parameters); } /// <summary> /// Parse a parenthesized parameter list. /// </summary> private CrefParameterListSyntax ParseCrefParameterList() { return (CrefParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: false); } /// <summary> /// Parse a bracketed parameter list. /// </summary> private CrefBracketedParameterListSyntax ParseBracketedCrefParameterList() { return (CrefBracketedParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: true); } /// <summary> /// Parse the parameter list (if any) of a cref member (name, indexer, operator, or conversion). /// </summary> private BaseCrefParameterListSyntax ParseBaseCrefParameterList(bool useSquareBrackets) { SyntaxKind openKind = useSquareBrackets ? SyntaxKind.OpenBracketToken : SyntaxKind.OpenParenToken; SyntaxKind closeKind = useSquareBrackets ? SyntaxKind.CloseBracketToken : SyntaxKind.CloseParenToken; if (CurrentToken.Kind != openKind) { return null; } SyntaxToken open = EatToken(openKind); var list = _pool.AllocateSeparated<CrefParameterSyntax>(); try { while (CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleCrefParameter()) { list.Add(ParseCrefParameter()); if (CurrentToken.Kind != closeKind) { SyntaxToken comma = EatToken(SyntaxKind.CommaToken); if (!comma.IsMissing || IsPossibleCrefParameter()) { // Only do this if it won't be last in the list. list.AddSeparator(comma); } else { // How could this scenario arise? If it does, just expand the if-condition. Debug.Assert(CurrentToken.Kind != SyntaxKind.CommaToken); } } } // NOTE: nothing follows a cref parameter list, so there's no reason to recover here. // Just let the cref-level recovery code handle any remaining tokens. SyntaxToken close = EatToken(closeKind); return useSquareBrackets ? (BaseCrefParameterListSyntax)SyntaxFactory.CrefBracketedParameterList(open, list, close) : SyntaxFactory.CrefParameterList(open, list, close); } finally { _pool.Free(list); } } /// <summary> /// True if the current token could be the beginning of a cref parameter. /// </summary> private bool IsPossibleCrefParameter() { SyntaxKind kind = this.CurrentToken.Kind; switch (kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.IdentifierToken: return true; default: return SyntaxFacts.IsPredefinedType(kind); } } /// <summary> /// Parse an element of a cref parameter list. /// </summary> /// <remarks> /// "ref" and "out" work, but "params", "this", and "__arglist" don't. /// </remarks> private CrefParameterSyntax ParseCrefParameter() { SyntaxToken refKindOpt = null; switch (CurrentToken.Kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: refKindOpt = EatToken(); break; } TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false); return SyntaxFactory.CrefParameter(refKindOpt, type); } /// <summary> /// Parse an identifier, optionally followed by an angle-bracketed list of type parameters. /// </summary> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> private SimpleNameSyntax ParseCrefName(bool typeArgumentsMustBeIdentifiers) { SyntaxToken identifierToken = EatToken(SyntaxKind.IdentifierToken); if (CurrentToken.Kind != SyntaxKind.LessThanToken) { return SyntaxFactory.IdentifierName(identifierToken); } var open = EatToken(); var list = _pool.AllocateSeparated<TypeSyntax>(); try { while (true) { TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers); if (typeArgumentsMustBeIdentifiers && typeSyntax.Kind != SyntaxKind.IdentifierName) { typeSyntax = this.AddError(typeSyntax, ErrorCode.WRN_ErrorOverride, new SyntaxDiagnosticInfo(ErrorCode.ERR_TypeParamMustBeIdentifier), $"{(int)ErrorCode.ERR_TypeParamMustBeIdentifier:d4}"); } list.Add(typeSyntax); var currentKind = CurrentToken.Kind; if (currentKind == SyntaxKind.CommaToken || currentKind == SyntaxKind.IdentifierToken || SyntaxFacts.IsPredefinedType(CurrentToken.Kind)) { // NOTE: if the current token is an identifier or predefined type, then we're // actually inserting a missing commas. list.AddSeparator(EatToken(SyntaxKind.CommaToken)); } else { break; } } SyntaxToken close = EatToken(SyntaxKind.GreaterThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics, forceWarning: true); return SyntaxFactory.GenericName(identifierToken, SyntaxFactory.TypeArgumentList(open, list, close)); } finally { _pool.Free(list); } } /// <summary> /// Parse a type. May include an alias, a predefined type, and/or a qualified name. /// </summary> /// <remarks> /// Pointer, nullable, or array types are only allowed if <paramref name="typeArgumentsMustBeIdentifiers"/> is false. /// Leaves a dot and a name unconsumed if the name is not followed by another dot /// and checkForMember is true. /// </remarks> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> /// <param name="checkForMember">True means that the last name should not be consumed /// if it is followed by a parameter list.</param> private TypeSyntax ParseCrefType(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) { TypeSyntax typeWithoutSuffix = ParseCrefTypeHelper(typeArgumentsMustBeIdentifiers, checkForMember); return typeArgumentsMustBeIdentifiers ? typeWithoutSuffix : ParseCrefTypeSuffix(typeWithoutSuffix); } /// <summary> /// Parse a type. May include an alias, a predefined type, and/or a qualified name. /// </summary> /// <remarks> /// No pointer, nullable, or array types. /// Leaves a dot and a name unconsumed if the name is not followed by another dot /// and checkForMember is true. /// </remarks> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> /// <param name="checkForMember">True means that the last name should not be consumed /// if it is followed by a parameter list.</param> private TypeSyntax ParseCrefTypeHelper(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) { NameSyntax leftName; if (SyntaxFacts.IsPredefinedType(CurrentToken.Kind)) { // e.g. "int" // NOTE: a predefined type will not fit into a NameSyntax, so we'll return // immediately. The upshot is that you can only dot into a predefined type // once (e.g. not "int.A.B"), which is fine because we know that none of them // have nested types. return SyntaxFactory.PredefinedType(EatToken()); } else if (CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonColonToken) { // e.g. "A::B" SyntaxToken alias = EatToken(); if (alias.ContextualKind == SyntaxKind.GlobalKeyword) { alias = ConvertToKeyword(alias); } alias = CheckFeatureAvailability(alias, MessageID.IDS_FeatureGlobalNamespace, forceWarning: true); SyntaxToken colonColon = EatToken(); SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers); leftName = SyntaxFactory.AliasQualifiedName(SyntaxFactory.IdentifierName(alias), colonColon, name); } else { // e.g. "A" ResetPoint resetPoint = GetResetPoint(); leftName = ParseCrefName(typeArgumentsMustBeIdentifiers); if (checkForMember && (leftName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken)) { // If this isn't the first part of a dotted name, then we prefer to represent it // as a MemberCrefSyntax. this.Reset(ref resetPoint); this.Release(ref resetPoint); return null; } this.Release(ref resetPoint); } while (CurrentToken.Kind == SyntaxKind.DotToken) { // NOTE: we make a lot of these, but we'll reset, at most, one time. ResetPoint resetPoint = GetResetPoint(); SyntaxToken dot = EatToken(); SimpleNameSyntax rightName = ParseCrefName(typeArgumentsMustBeIdentifiers); if (checkForMember && (rightName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken)) { this.Reset(ref resetPoint); // Go back to before the dot - it must have been the trailing dot. this.Release(ref resetPoint); return leftName; } this.Release(ref resetPoint); leftName = SyntaxFactory.QualifiedName(leftName, dot, rightName); } return leftName; } /// <summary> /// Once the name part of a type (including type parameter/argument lists) is parsed, /// we need to consume ?, *, and rank specifiers. /// </summary> private TypeSyntax ParseCrefTypeSuffix(TypeSyntax type) { if (CurrentToken.Kind == SyntaxKind.QuestionToken) { type = SyntaxFactory.NullableType(type, EatToken()); } while (CurrentToken.Kind == SyntaxKind.AsteriskToken) { type = SyntaxFactory.PointerType(type, EatToken()); } if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var omittedArraySizeExpressionInstance = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var rankList = _pool.Allocate<ArrayRankSpecifierSyntax>(); try { while (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { SyntaxToken open = EatToken(); var dimensionList = _pool.AllocateSeparated<ExpressionSyntax>(); try { while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // NOTE: trivia will be attached to comma, not omitted array size dimensionList.Add(omittedArraySizeExpressionInstance); dimensionList.AddSeparator(this.EatToken()); } else { // CONSIDER: if we expect people to try to put expressions in between // the commas, then it might be more reasonable to recover by skipping // tokens until we hit a CloseBracketToken (or some other terminator). break; } } // Don't end on a comma. // If the omitted size would be the only element, then skip it unless sizes were expected. if ((dimensionList.Count & 1) == 0) { dimensionList.Add(omittedArraySizeExpressionInstance); } // Eat the close brace and we're done. var close = this.EatToken(SyntaxKind.CloseBracketToken); rankList.Add(SyntaxFactory.ArrayRankSpecifier(open, dimensionList, close)); } finally { _pool.Free(dimensionList); } } type = SyntaxFactory.ArrayType(type, rankList); } finally { _pool.Free(rankList); } } return type; } /// <summary> /// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment. /// </summary> private bool IsEndOfCrefAttribute { get { switch (CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: return (this.Mode & LexerMode.XmlCrefQuote) == LexerMode.XmlCrefQuote; case SyntaxKind.DoubleQuoteToken: return (this.Mode & LexerMode.XmlCrefDoubleQuote) == LexerMode.XmlCrefDoubleQuote; case SyntaxKind.EndOfFileToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; case SyntaxKind.BadToken: // If it's a real '<' (not &lt;, etc), then we assume it's the beginning // of the next XML element. return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) || IsNonAsciiQuotationMark(CurrentToken); default: return false; } } } /// <summary> /// Convenience method for checking the mode. /// </summary> private bool InCref { get { switch (this.Mode & (LexerMode.XmlCrefDoubleQuote | LexerMode.XmlCrefQuote)) { case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: return true; default: return false; } } } #endregion Cref #region Name attribute values private IdentifierNameSyntax ParseNameAttributeValue() { // Never report a parse error - just fail to bind the name later on. SyntaxToken identifierToken = this.EatToken(SyntaxKind.IdentifierToken, reportError: false); if (!IsEndOfNameAttribute) { var badTokens = _pool.Allocate<SyntaxToken>(); while (!IsEndOfNameAttribute) { badTokens.Add(this.EatToken()); } identifierToken = AddTrailingSkippedSyntax(identifierToken, badTokens.ToListNode()); _pool.Free(badTokens); } return SyntaxFactory.IdentifierName(identifierToken); } /// <summary> /// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment. /// </summary> private bool IsEndOfNameAttribute { get { switch (CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: return (this.Mode & LexerMode.XmlNameQuote) == LexerMode.XmlNameQuote; case SyntaxKind.DoubleQuoteToken: return (this.Mode & LexerMode.XmlNameDoubleQuote) == LexerMode.XmlNameDoubleQuote; case SyntaxKind.EndOfFileToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; case SyntaxKind.BadToken: // If it's a real '<' (not &lt;, etc), then we assume it's the beginning // of the next XML element. return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) || IsNonAsciiQuotationMark(CurrentToken); default: return false; } } } #endregion Name attribute values } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { using Microsoft.CodeAnalysis.Syntax.InternalSyntax; // TODO: The Xml parser recognizes most commonplace XML, according to the XML spec. // It does not recognize the following: // // * Document Type Definition // <!DOCTYPE ... > // * Element Type Declaration, Attribute-List Declarations, Entity Declarations, Notation Declarations // <!ELEMENT ... > // <!ATTLIST ... > // <!ENTITY ... > // <!NOTATION ... > // * Conditional Sections // <![INCLUDE[ ... ]]> // <![IGNORE[ ... ]]> // // This probably does not matter. However, if it becomes necessary to recognize any // of these bits of XML, the most sensible thing to do is probably to scan them without // trying to understand them, e.g. like comments or CDATA, so that they are available // to whoever processes these comments and do not produce an error. internal class DocumentationCommentParser : SyntaxParser { private readonly SyntaxListPool _pool = new SyntaxListPool(); private bool _isDelimited; internal DocumentationCommentParser(Lexer lexer, LexerMode modeflags) : base(lexer, LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags, null, null, true) { _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; } internal void ReInitialize(LexerMode modeflags) { base.ReInitialize(); this.Mode = LexerMode.XmlDocComment | LexerMode.XmlDocCommentLocationStart | modeflags; _isDelimited = (modeflags & LexerMode.XmlDocCommentStyleDelimited) != 0; } private LexerMode SetMode(LexerMode mode) { var tmp = this.Mode; this.Mode = mode | (tmp & (LexerMode.MaskXmlDocCommentLocation | LexerMode.MaskXmlDocCommentStyle)); return tmp; } private void ResetMode(LexerMode mode) { this.Mode = mode; } public DocumentationCommentTriviaSyntax ParseDocumentationComment(out bool isTerminated) { var nodes = _pool.Allocate<XmlNodeSyntax>(); try { this.ParseXmlNodes(nodes); // It's possible that we finish parsing the xml, and we are still left in the middle // of an Xml comment. For example, // // /// <goo></goo></uhoh> // ^ // In this case, we stop at the caret. We need to ensure that we consume the remainder // of the doc comment here, since otherwise we will return the lexer to the state // where it recognizes C# tokens, which means that C# parser will get the </uhoh>, // which is not at all what we want. if (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) { this.ParseRemainder(nodes); } var eoc = this.EatToken(SyntaxKind.EndOfDocumentationCommentToken); isTerminated = !_isDelimited || (eoc.LeadingTrivia.Count > 0 && eoc.LeadingTrivia[eoc.LeadingTrivia.Count - 1].ToString() == "*/"); SyntaxKind kind = _isDelimited ? SyntaxKind.MultiLineDocumentationCommentTrivia : SyntaxKind.SingleLineDocumentationCommentTrivia; return SyntaxFactory.DocumentationCommentTrivia(kind, nodes.ToList(), eoc); } finally { _pool.Free(nodes); } } public void ParseRemainder(SyntaxListBuilder<XmlNodeSyntax> nodes) { bool endTag = this.CurrentToken.Kind == SyntaxKind.LessThanSlashToken; var saveMode = this.SetMode(LexerMode.XmlCDataSectionText); var textTokens = _pool.Allocate(); try { while (this.CurrentToken.Kind != SyntaxKind.EndOfDocumentationCommentToken) { var token = this.EatToken(); // TODO: It is possible that a non-literal gets in here. ]]>, specifically. Is that ok? textTokens.Add(token); } var allRemainderText = SyntaxFactory.XmlText(textTokens.ToList()); XmlParseErrorCode code = endTag ? XmlParseErrorCode.XML_EndTagNotExpected : XmlParseErrorCode.XML_ExpectedEndOfXml; allRemainderText = WithAdditionalDiagnostics(allRemainderText, new XmlSyntaxDiagnosticInfo(0, 1, code)); nodes.Add(allRemainderText); } finally { _pool.Free(textTokens); } this.ResetMode(saveMode); } private void ParseXmlNodes(SyntaxListBuilder<XmlNodeSyntax> nodes) { while (true) { var node = this.ParseXmlNode(); if (node == null) { return; } nodes.Add(node); } } private XmlNodeSyntax ParseXmlNode() { switch (this.CurrentToken.Kind) { case SyntaxKind.XmlTextLiteralToken: case SyntaxKind.XmlTextLiteralNewLineToken: case SyntaxKind.XmlEntityLiteralToken: return this.ParseXmlText(); case SyntaxKind.LessThanToken: return this.ParseXmlElement(); case SyntaxKind.XmlCommentStartToken: return this.ParseXmlComment(); case SyntaxKind.XmlCDataStartToken: return this.ParseXmlCDataSection(); case SyntaxKind.XmlProcessingInstructionStartToken: return this.ParseXmlProcessingInstruction(); case SyntaxKind.EndOfDocumentationCommentToken: return null; default: // This means we have some unrecognized token. We probably need to give an error. return null; } } private bool IsXmlNodeStartOrStop() { switch (this.CurrentToken.Kind) { case SyntaxKind.LessThanToken: case SyntaxKind.LessThanSlashToken: case SyntaxKind.XmlCommentStartToken: case SyntaxKind.XmlCDataStartToken: case SyntaxKind.XmlProcessingInstructionStartToken: case SyntaxKind.GreaterThanToken: case SyntaxKind.SlashGreaterThanToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; default: return false; } } private XmlNodeSyntax ParseXmlText() { var textTokens = _pool.Allocate(); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken) { textTokens.Add(this.EatToken()); } var list = textTokens.ToList(); _pool.Free(textTokens); return SyntaxFactory.XmlText(list); } private XmlNodeSyntax ParseXmlElement() { var lessThan = this.EatToken(SyntaxKind.LessThanToken); // guaranteed var saveMode = this.SetMode(LexerMode.XmlElementTag); var name = this.ParseXmlName(); if (lessThan.GetTrailingTriviaWidth() > 0 || name.GetLeadingTriviaWidth() > 0) { // The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>' name = this.WithXmlParseError(name, XmlParseErrorCode.XML_InvalidWhitespace); } var attrs = _pool.Allocate<XmlAttributeSyntax>(); try { this.ParseXmlAttributes(ref name, attrs); if (this.CurrentToken.Kind == SyntaxKind.GreaterThanToken) { var startTag = SyntaxFactory.XmlElementStartTag(lessThan, name, attrs, this.EatToken()); this.SetMode(LexerMode.XmlDocComment); var nodes = _pool.Allocate<XmlNodeSyntax>(); try { this.ParseXmlNodes(nodes); XmlNameSyntax endName; SyntaxToken greaterThan; // end tag var lessThanSlash = this.EatToken(SyntaxKind.LessThanSlashToken, reportError: false); // If we didn't see "</", then we can't really be confident that this is actually an end tag, // so just insert a missing one. if (lessThanSlash.IsMissing) { this.ResetMode(saveMode); lessThanSlash = this.WithXmlParseError(lessThanSlash, XmlParseErrorCode.XML_EndTagExpected, name.ToString()); endName = SyntaxFactory.XmlName(prefix: null, localName: SyntaxFactory.MissingToken(SyntaxKind.IdentifierToken)); greaterThan = SyntaxFactory.MissingToken(SyntaxKind.GreaterThanToken); } else { this.SetMode(LexerMode.XmlElementTag); endName = this.ParseXmlName(); if (lessThanSlash.GetTrailingTriviaWidth() > 0 || endName.GetLeadingTriviaWidth() > 0) { // The Xml spec disallows whitespace here: STag ::= '<' Name (S Attribute)* S? '>' endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_InvalidWhitespace); } if (!endName.IsMissing && !MatchingXmlNames(name, endName)) { endName = this.WithXmlParseError(endName, XmlParseErrorCode.XML_ElementTypeMatch, endName.ToString(), name.ToString()); } // if we don't see the greater than token then skip the badness until we do or abort if (this.CurrentToken.Kind != SyntaxKind.GreaterThanToken) { this.SkipBadTokens(ref endName, null, p => p.CurrentToken.Kind != SyntaxKind.GreaterThanToken, p => p.IsXmlNodeStartOrStop(), XmlParseErrorCode.XML_InvalidToken ); } greaterThan = this.EatToken(SyntaxKind.GreaterThanToken); } var endTag = SyntaxFactory.XmlElementEndTag(lessThanSlash, endName, greaterThan); this.ResetMode(saveMode); return SyntaxFactory.XmlElement(startTag, nodes.ToList(), endTag); } finally { _pool.Free(nodes); } } else { var slashGreater = this.EatToken(SyntaxKind.SlashGreaterThanToken, false); if (slashGreater.IsMissing && !name.IsMissing) { slashGreater = this.WithXmlParseError(slashGreater, XmlParseErrorCode.XML_ExpectedEndOfTag, name.ToString()); } this.ResetMode(saveMode); return SyntaxFactory.XmlEmptyElement(lessThan, name, attrs, slashGreater); } } finally { _pool.Free(attrs); } } private static bool MatchingXmlNames(XmlNameSyntax name, XmlNameSyntax endName) { // PERF: because of deduplication we often get the same name for name and endName, // so we will check for such case first before materializing text for entire nodes // and comparing that. if (name == endName) { return true; } // before doing ToString, check if // all nodes contributing to ToString are recursively the same // NOTE: leading and trailing trivia do not contribute to ToString if (!name.HasLeadingTrivia && !endName.HasTrailingTrivia && name.IsEquivalentTo(endName)) { return true; } return name.ToString() == endName.ToString(); } // assuming this is not used concurrently private readonly HashSet<string> _attributesSeen = new HashSet<string>(); private void ParseXmlAttributes(ref XmlNameSyntax elementName, SyntaxListBuilder<XmlAttributeSyntax> attrs) { _attributesSeen.Clear(); while (true) { if (this.CurrentToken.Kind == SyntaxKind.IdentifierToken) { var attr = this.ParseXmlAttribute(elementName); string attrName = attr.Name.ToString(); if (_attributesSeen.Contains(attrName)) { attr = this.WithXmlParseError(attr, XmlParseErrorCode.XML_DuplicateAttribute, attrName); } else { _attributesSeen.Add(attrName); } attrs.Add(attr); } else { var skip = this.SkipBadTokens(ref elementName, attrs, // not expected condition p => p.CurrentToken.Kind != SyntaxKind.IdentifierName, // abort condition (looks like something we might understand later) p => p.CurrentToken.Kind == SyntaxKind.GreaterThanToken || p.CurrentToken.Kind == SyntaxKind.SlashGreaterThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanToken || p.CurrentToken.Kind == SyntaxKind.LessThanSlashToken || p.CurrentToken.Kind == SyntaxKind.EndOfDocumentationCommentToken || p.CurrentToken.Kind == SyntaxKind.EndOfFileToken, XmlParseErrorCode.XML_InvalidToken ); if (skip == SkipResult.Abort) { break; } } } } private enum SkipResult { Continue, Abort } private SkipResult SkipBadTokens<T>( ref T startNode, SyntaxListBuilder list, Func<DocumentationCommentParser, bool> isNotExpectedFunction, Func<DocumentationCommentParser, bool> abortFunction, XmlParseErrorCode error ) where T : CSharpSyntaxNode { var badTokens = default(SyntaxListBuilder<SyntaxToken>); bool hasError = false; try { SkipResult result = SkipResult.Continue; while (isNotExpectedFunction(this)) { if (abortFunction(this)) { result = SkipResult.Abort; break; } if (badTokens.IsNull) { badTokens = _pool.Allocate<SyntaxToken>(); } var token = this.EatToken(); if (!hasError) { token = this.WithXmlParseError(token, error, token.ToString()); hasError = true; } badTokens.Add(token); } if (!badTokens.IsNull && badTokens.Count > 0) { // use skipped text since cannot nest structured trivia under structured trivia if (list == null || list.Count == 0) { startNode = AddTrailingSkippedSyntax(startNode, badTokens.ToListNode()); } else { list[list.Count - 1] = AddTrailingSkippedSyntax((CSharpSyntaxNode)list[list.Count - 1], badTokens.ToListNode()); } return result; } else { // somehow we did not consume anything, so tell caller to abort parse rule return SkipResult.Abort; } } finally { if (!badTokens.IsNull) { _pool.Free(badTokens); } } } private XmlAttributeSyntax ParseXmlAttribute(XmlNameSyntax elementName) { var attrName = this.ParseXmlName(); if (attrName.GetLeadingTriviaWidth() == 0) { // The Xml spec requires whitespace here: STag ::= '<' Name (S Attribute)* S? '>' attrName = this.WithXmlParseError(attrName, XmlParseErrorCode.XML_WhitespaceMissing); } var equals = this.EatToken(SyntaxKind.EqualsToken, false); if (equals.IsMissing) { equals = this.WithXmlParseError(equals, XmlParseErrorCode.XML_MissingEqualsAttribute); switch (this.CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: case SyntaxKind.DoubleQuoteToken: // There could be a value coming up, let's keep parsing. break; default: // This is probably not a complete attribute. return SyntaxFactory.XmlTextAttribute( attrName, equals, SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken), default(SyntaxList<SyntaxToken>), SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken)); } } SyntaxToken startQuote; SyntaxToken endQuote; string attrNameText = attrName.LocalName.ValueText; bool hasNoPrefix = attrName.Prefix == null; if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.CrefAttributeName) && !IsVerbatimCref()) { CrefSyntax cref; this.ParseCrefAttribute(out startQuote, out cref, out endQuote); return SyntaxFactory.XmlCrefAttribute(attrName, equals, startQuote, cref, endQuote); } else if (hasNoPrefix && DocumentationCommentXmlNames.AttributeEquals(attrNameText, DocumentationCommentXmlNames.NameAttributeName) && XmlElementSupportsNameAttribute(elementName)) { IdentifierNameSyntax identifier; this.ParseNameAttribute(out startQuote, out identifier, out endQuote); return SyntaxFactory.XmlNameAttribute(attrName, equals, startQuote, identifier, endQuote); } else { var textTokens = _pool.Allocate<SyntaxToken>(); try { this.ParseXmlAttributeText(out startQuote, textTokens, out endQuote); return SyntaxFactory.XmlTextAttribute(attrName, equals, startQuote, textTokens, endQuote); } finally { _pool.Free(textTokens); } } } private static bool XmlElementSupportsNameAttribute(XmlNameSyntax elementName) { if (elementName.Prefix != null) { return false; } string localName = elementName.LocalName.ValueText; return DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.ParameterReferenceElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterElementName) || DocumentationCommentXmlNames.ElementEquals(localName, DocumentationCommentXmlNames.TypeParameterReferenceElementName); } private bool IsVerbatimCref() { // As in XMLDocWriter::ReplaceReferences, if the first character of the value is not colon and the second character // is, then don't process the cref - just emit it as-is. bool isVerbatim = false; var resetPoint = this.GetResetPoint(); SyntaxToken openQuote = EatToken(this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken); // NOTE: Don't need to save mode, since we're already using a reset point. this.SetMode(LexerMode.XmlCharacter); SyntaxToken current = this.CurrentToken; if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) && current.ValueText != SyntaxFacts.GetText(openQuote.Kind) && current.ValueText != ":") { EatToken(); current = this.CurrentToken; if ((current.Kind == SyntaxKind.XmlTextLiteralToken || current.Kind == SyntaxKind.XmlEntityLiteralToken) && current.ValueText == ":") { isVerbatim = true; } } this.Reset(ref resetPoint); this.Release(ref resetPoint); return isVerbatim; } private void ParseCrefAttribute(out SyntaxToken startQuote, out CrefSyntax cref, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlCrefQuote : LexerMode.XmlCrefDoubleQuote); cref = this.ParseCrefAttributeValue(); this.ResetMode(saveMode); } endQuote = ParseXmlAttributeEndQuote(quoteKind); } private void ParseNameAttribute(out SyntaxToken startQuote, out IdentifierNameSyntax identifier, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlNameQuote : LexerMode.XmlNameDoubleQuote); identifier = this.ParseNameAttributeValue(); this.ResetMode(saveMode); } endQuote = ParseXmlAttributeEndQuote(quoteKind); } private void ParseXmlAttributeText(out SyntaxToken startQuote, SyntaxListBuilder<SyntaxToken> textTokens, out SyntaxToken endQuote) { startQuote = ParseXmlAttributeStartQuote(); SyntaxKind quoteKind = startQuote.Kind; // NOTE: Being a bit sneaky here - if the width isn't 0, we consumed something else in // place of the quote and we should continue parsing the attribute. if (startQuote.IsMissing && startQuote.FullWidth == 0) { endQuote = SyntaxFactory.MissingToken(quoteKind); } else { var saveMode = this.SetMode(quoteKind == SyntaxKind.SingleQuoteToken ? LexerMode.XmlAttributeTextQuote : LexerMode.XmlAttributeTextDoubleQuote); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.XmlEntityLiteralToken || this.CurrentToken.Kind == SyntaxKind.LessThanToken) { var token = this.EatToken(); if (token.Kind == SyntaxKind.LessThanToken) { // TODO: It is possible that a non-literal gets in here. <, specifically. Is that ok? token = this.WithXmlParseError(token, XmlParseErrorCode.XML_LessThanInAttributeValue); } textTokens.Add(token); } this.ResetMode(saveMode); // NOTE: This will never consume a non-ascii quote, since non-ascii quotes // are legal in the attribute value and are consumed by the preceding loop. endQuote = ParseXmlAttributeEndQuote(quoteKind); } } private SyntaxToken ParseXmlAttributeStartQuote() { if (IsNonAsciiQuotationMark(this.CurrentToken)) { return SkipNonAsciiQuotationMark(); } var quoteKind = this.CurrentToken.Kind == SyntaxKind.SingleQuoteToken ? SyntaxKind.SingleQuoteToken : SyntaxKind.DoubleQuoteToken; var startQuote = this.EatToken(quoteKind, reportError: false); if (startQuote.IsMissing) { startQuote = this.WithXmlParseError(startQuote, XmlParseErrorCode.XML_StringLiteralNoStartQuote); } return startQuote; } private SyntaxToken ParseXmlAttributeEndQuote(SyntaxKind quoteKind) { if (IsNonAsciiQuotationMark(this.CurrentToken)) { return SkipNonAsciiQuotationMark(); } var endQuote = this.EatToken(quoteKind, reportError: false); if (endQuote.IsMissing) { endQuote = this.WithXmlParseError(endQuote, XmlParseErrorCode.XML_StringLiteralNoEndQuote); } return endQuote; } private SyntaxToken SkipNonAsciiQuotationMark() { var quote = SyntaxFactory.MissingToken(SyntaxKind.DoubleQuoteToken); quote = AddTrailingSkippedSyntax(quote, EatToken()); quote = this.WithXmlParseError(quote, XmlParseErrorCode.XML_StringLiteralNonAsciiQuote); return quote; } /// <summary> /// These aren't acceptable in place of ASCII quotation marks in XML, /// but we want to consume them (and produce an appropriate error) if /// they occur in a place where a quotation mark is legal. /// </summary> private static bool IsNonAsciiQuotationMark(SyntaxToken token) { return token.Text.Length == 1 && SyntaxFacts.IsNonAsciiQuotationMark(token.Text[0]); } private XmlNameSyntax ParseXmlName() { var id = this.EatToken(SyntaxKind.IdentifierToken); XmlPrefixSyntax prefix = null; if (this.CurrentToken.Kind == SyntaxKind.ColonToken) { var colon = this.EatToken(); int prefixTrailingWidth = id.GetTrailingTriviaWidth(); int colonLeadingWidth = colon.GetLeadingTriviaWidth(); if (prefixTrailingWidth > 0 || colonLeadingWidth > 0) { // NOTE: offset is relative to full-span start of colon (i.e. before leading trivia). int offset = -prefixTrailingWidth; int width = prefixTrailingWidth + colonLeadingWidth; colon = WithAdditionalDiagnostics(colon, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace)); } prefix = SyntaxFactory.XmlPrefix(id, colon); id = this.EatToken(SyntaxKind.IdentifierToken); int colonTrailingWidth = colon.GetTrailingTriviaWidth(); int localNameLeadingWidth = id.GetLeadingTriviaWidth(); if (colonTrailingWidth > 0 || localNameLeadingWidth > 0) { // NOTE: offset is relative to full-span start of identifier (i.e. before leading trivia). int offset = -colonTrailingWidth; int width = colonTrailingWidth + localNameLeadingWidth; id = WithAdditionalDiagnostics(id, new XmlSyntaxDiagnosticInfo(offset, width, XmlParseErrorCode.XML_InvalidWhitespace)); // CONSIDER: Another interpretation would be that the local part of this name is a missing identifier and the identifier // we've just consumed is actually part of something else (e.g. an attribute name). } } return SyntaxFactory.XmlName(prefix, id); } private XmlCommentSyntax ParseXmlComment() { var lessThanExclamationMinusMinusToken = this.EatToken(SyntaxKind.XmlCommentStartToken); var saveMode = this.SetMode(LexerMode.XmlCommentText); var textTokens = _pool.Allocate<SyntaxToken>(); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken || this.CurrentToken.Kind == SyntaxKind.MinusMinusToken) { var token = this.EatToken(); if (token.Kind == SyntaxKind.MinusMinusToken) { // TODO: It is possible that a non-literal gets in here. --, specifically. Is that ok? token = this.WithXmlParseError(token, XmlParseErrorCode.XML_IncorrectComment); } textTokens.Add(token); } var list = textTokens.ToList(); _pool.Free(textTokens); var minusMinusGreaterThanToken = this.EatToken(SyntaxKind.XmlCommentEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, list, minusMinusGreaterThanToken); } private XmlCDataSectionSyntax ParseXmlCDataSection() { var startCDataToken = this.EatToken(SyntaxKind.XmlCDataStartToken); var saveMode = this.SetMode(LexerMode.XmlCDataSectionText); var textTokens = new SyntaxListBuilder<SyntaxToken>(10); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) { textTokens.Add(this.EatToken()); } var endCDataToken = this.EatToken(SyntaxKind.XmlCDataEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); } private XmlProcessingInstructionSyntax ParseXmlProcessingInstruction() { var startProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionStartToken); var saveMode = this.SetMode(LexerMode.XmlElementTag); //this mode accepts names var name = this.ParseXmlName(); // NOTE: The XML spec says that name cannot be "xml" (case-insensitive comparison), // but Dev10 does not enforce this. this.SetMode(LexerMode.XmlProcessingInstructionText); //this mode consumes text var textTokens = new SyntaxListBuilder<SyntaxToken>(10); while (this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralToken || this.CurrentToken.Kind == SyntaxKind.XmlTextLiteralNewLineToken) { var textToken = this.EatToken(); // NOTE: The XML spec says that the each text token must begin with a whitespace // character, but Dev10 does not enforce this. textTokens.Add(textToken); } var endProcessingInstructionToken = this.EatToken(SyntaxKind.XmlProcessingInstructionEndToken); this.ResetMode(saveMode); return SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); } protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual, int offset, int length) { // NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride. if (InCref) { SyntaxDiagnosticInfo rawInfo = base.GetExpectedTokenError(expected, actual, offset, length); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(rawInfo.Offset, rawInfo.Width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); return crefInfo; } switch (expected) { case SyntaxKind.IdentifierToken: return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_ExpectedIdentifier); default: return new XmlSyntaxDiagnosticInfo(offset, length, XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); } } protected override SyntaxDiagnosticInfo GetExpectedTokenError(SyntaxKind expected, SyntaxKind actual) { // NOTE: There are no errors in crefs - only warnings. We accomplish this by wrapping every diagnostic in ErrorCode.WRN_ErrorOverride. if (InCref) { int offset, width; this.GetDiagnosticSpanForMissingToken(out offset, out width); return GetExpectedTokenError(expected, actual, offset, width); } switch (expected) { case SyntaxKind.IdentifierToken: return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_ExpectedIdentifier); default: return new XmlSyntaxDiagnosticInfo(XmlParseErrorCode.XML_InvalidToken, SyntaxFacts.GetText(actual)); } } private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code)); } private TNode WithXmlParseError<TNode>(TNode node, XmlParseErrorCode code, params string[] args) where TNode : CSharpSyntaxNode { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args)); } private SyntaxToken WithXmlParseError(SyntaxToken node, XmlParseErrorCode code, params string[] args) { return WithAdditionalDiagnostics(node, new XmlSyntaxDiagnosticInfo(0, node.Width, code, args)); } protected override TNode WithAdditionalDiagnostics<TNode>(TNode node, params DiagnosticInfo[] diagnostics) { // Don't attach any diagnostics to syntax nodes within a documentation comment if the DocumentationMode // is not at least Diagnose. return Options.DocumentationMode >= DocumentationMode.Diagnose ? base.WithAdditionalDiagnostics<TNode>(node, diagnostics) : node; } #region Cref /// <summary> /// ACASEY: This grammar is derived from the behavior and sources of the native compiler. /// Tokens start with underscores (I've cheated for _PredefinedTypeToken, which is not actually a /// SyntaxKind), "*" indicates "0 or more", "?" indicates "0 or 1", and parentheses are for grouping. /// /// Cref = CrefType _DotToken CrefMember /// | CrefType /// | CrefMember /// | CrefFirstType _OpenParenToken CrefParameterList? _CloseParenToken /// CrefName = _IdentifierToken (_LessThanToken _IdentifierToken (_CommaToken _IdentifierToken)* _GreaterThanToken)? /// CrefFirstType = ((_IdentifierToken _ColonColonToken)? CrefName) /// | _PredefinedTypeToken /// CrefType = CrefFirstType (_DotToken CrefName)* /// CrefMember = CrefName (_OpenParenToken CrefParameterList? _CloseParenToken)? /// | _ThisKeyword (_OpenBracketToken CrefParameterList _CloseBracketToken)? /// | _OperatorKeyword _OperatorToken (_OpenParenToken CrefParameterList? _CloseParenToken)? /// | (_ImplicitKeyword | _ExplicitKeyword) _OperatorKeyword CrefParameterType (_OpenParenToken CrefParameterList? _CloseParenToken)? /// CrefParameterList = CrefParameter (_CommaToken CrefParameter)* /// CrefParameter = (_RefKeyword | _OutKeyword)? CrefParameterType /// CrefParameterType = CrefParameterType2 _QuestionToken? _AsteriskToken* (_OpenBracketToken _CommaToken* _CloseBracketToken)* /// CrefParameterType2 = (((_IdentifierToken _ColonColonToken)? CrefParameterType3) | _PredefinedTypeToken) (_DotToken CrefParameterType3)* /// CrefParameterType3 = _IdentifierToken (_LessThanToken CrefParameterType (_CommaToken CrefParameterType)* _GreaterThanToken)? /// /// NOTE: type parameters, not type arguments /// NOTE: the first production of Cref is preferred to the other two /// NOTE: pointer, array, and nullable types only work in parameters /// NOTE: CrefParameterType2 and CrefParameterType3 correspond to CrefType and CrefName, respectively. /// Since the only difference is that they accept non-identifier type arguments, this is accomplished /// using parameters on the parsing methods (rather than whole new methods). /// </summary> private CrefSyntax ParseCrefAttributeValue() { CrefSyntax result; TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: true, checkForMember: true); if (type == null) { result = ParseMemberCref(); } else if (IsEndOfCrefAttribute) { result = SyntaxFactory.TypeCref(type); } else if (type.Kind != SyntaxKind.QualifiedName && this.CurrentToken.Kind == SyntaxKind.OpenParenToken) { // Special case for crefs like "string()" and "A::B()". CrefParameterListSyntax parameters = ParseCrefParameterList(); result = SyntaxFactory.NameMemberCref(type, parameters); } else { SyntaxToken dot = EatToken(SyntaxKind.DotToken); MemberCrefSyntax member = ParseMemberCref(); result = SyntaxFactory.QualifiedCref(type, dot, member); } bool needOverallError = !IsEndOfCrefAttribute || result.ContainsDiagnostics; if (!IsEndOfCrefAttribute) { var badTokens = _pool.Allocate<SyntaxToken>(); while (!IsEndOfCrefAttribute) { badTokens.Add(this.EatToken()); } result = AddTrailingSkippedSyntax(result, badTokens.ToListNode()); _pool.Free(badTokens); } if (needOverallError) { result = this.AddError(result, ErrorCode.WRN_BadXMLRefSyntax, result.ToFullString()); } return result; } /// <summary> /// Parse the custom cref syntax for a named member (method, property, etc), /// an indexer, an overloadable operator, or a user-defined conversion. /// </summary> private MemberCrefSyntax ParseMemberCref() { switch (CurrentToken.Kind) { case SyntaxKind.ThisKeyword: return ParseIndexerMemberCref(); case SyntaxKind.OperatorKeyword: return ParseOperatorMemberCref(); case SyntaxKind.ExplicitKeyword: case SyntaxKind.ImplicitKeyword: return ParseConversionOperatorMemberCref(); default: return ParseNameMemberCref(); } } /// <summary> /// Parse a named member (method, property, etc), with optional type /// parameters and regular parameters. /// </summary> private NameMemberCrefSyntax ParseNameMemberCref() { SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers: true); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.NameMemberCref(name, parameters); } /// <summary> /// Parse an indexer member, with optional parameters. /// </summary> private IndexerMemberCrefSyntax ParseIndexerMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.ThisKeyword); SyntaxToken thisKeyword = EatToken(); CrefBracketedParameterListSyntax parameters = ParseBracketedCrefParameterList(); return SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); } /// <summary> /// Parse an overloadable operator, with optional parameters. /// </summary> private OperatorMemberCrefSyntax ParseOperatorMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.OperatorKeyword); SyntaxToken operatorKeyword = EatToken(); SyntaxToken operatorToken; if (SyntaxFacts.IsAnyOverloadableOperator(CurrentToken.Kind)) { operatorToken = EatToken(); } else { operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); // Grab the offset and width before we consume the invalid keyword and change our position. int offset; int width; GetDiagnosticSpanForMissingToken(out offset, out width); if (SyntaxFacts.IsUnaryOperatorDeclarationToken(CurrentToken.Kind) || SyntaxFacts.IsBinaryExpressionOperatorToken(CurrentToken.Kind)) { operatorToken = AddTrailingSkippedSyntax(operatorToken, EatToken()); } SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo); } // Have to fake >> because it looks like the closing of nested type parameter lists (e.g. A<A<T>>). // Have to fake >= so the lexer doesn't mishandle >>=. if (operatorToken.Kind == SyntaxKind.GreaterThanToken && operatorToken.GetTrailingTriviaWidth() == 0 && CurrentToken.GetLeadingTriviaWidth() == 0) { if (CurrentToken.Kind == SyntaxKind.GreaterThanToken) { var operatorToken2 = this.EatToken(); operatorToken = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); } else if (CurrentToken.Kind == SyntaxKind.EqualsToken) { var operatorToken2 = this.EatToken(); operatorToken = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanEqualsToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); } else if (CurrentToken.Kind == SyntaxKind.GreaterThanEqualsToken) { var operatorToken2 = this.EatToken(); var nonOverloadableOperator = SyntaxFactory.Token( operatorToken.GetLeadingTrivia(), SyntaxKind.GreaterThanGreaterThanEqualsToken, operatorToken.Text + operatorToken2.Text, operatorToken.ValueText + operatorToken2.ValueText, operatorToken2.GetTrailingTrivia()); operatorToken = SyntaxFactory.MissingToken(SyntaxKind.PlusToken); // Add non-overloadable operator as skipped token. operatorToken = AddTrailingSkippedSyntax(operatorToken, nonOverloadableOperator); // Add an appropriate diagnostic. const int offset = 0; int width = nonOverloadableOperator.Width; SyntaxDiagnosticInfo rawInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.ERR_OvlOperatorExpected); SyntaxDiagnosticInfo crefInfo = new SyntaxDiagnosticInfo(offset, width, ErrorCode.WRN_ErrorOverride, rawInfo, rawInfo.Code); operatorToken = WithAdditionalDiagnostics(operatorToken, crefInfo); } } Debug.Assert(SyntaxFacts.IsAnyOverloadableOperator(operatorToken.Kind)); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters); } /// <summary> /// Parse a user-defined conversion, with optional parameters. /// </summary> private ConversionOperatorMemberCrefSyntax ParseConversionOperatorMemberCref() { Debug.Assert(CurrentToken.Kind == SyntaxKind.ExplicitKeyword || CurrentToken.Kind == SyntaxKind.ImplicitKeyword); SyntaxToken implicitOrExplicit = EatToken(); SyntaxToken operatorKeyword = EatToken(SyntaxKind.OperatorKeyword); TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false); CrefParameterListSyntax parameters = ParseCrefParameterList(); return SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicit, operatorKeyword, type, parameters); } /// <summary> /// Parse a parenthesized parameter list. /// </summary> private CrefParameterListSyntax ParseCrefParameterList() { return (CrefParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: false); } /// <summary> /// Parse a bracketed parameter list. /// </summary> private CrefBracketedParameterListSyntax ParseBracketedCrefParameterList() { return (CrefBracketedParameterListSyntax)ParseBaseCrefParameterList(useSquareBrackets: true); } /// <summary> /// Parse the parameter list (if any) of a cref member (name, indexer, operator, or conversion). /// </summary> private BaseCrefParameterListSyntax ParseBaseCrefParameterList(bool useSquareBrackets) { SyntaxKind openKind = useSquareBrackets ? SyntaxKind.OpenBracketToken : SyntaxKind.OpenParenToken; SyntaxKind closeKind = useSquareBrackets ? SyntaxKind.CloseBracketToken : SyntaxKind.CloseParenToken; if (CurrentToken.Kind != openKind) { return null; } SyntaxToken open = EatToken(openKind); var list = _pool.AllocateSeparated<CrefParameterSyntax>(); try { while (CurrentToken.Kind == SyntaxKind.CommaToken || IsPossibleCrefParameter()) { list.Add(ParseCrefParameter()); if (CurrentToken.Kind != closeKind) { SyntaxToken comma = EatToken(SyntaxKind.CommaToken); if (!comma.IsMissing || IsPossibleCrefParameter()) { // Only do this if it won't be last in the list. list.AddSeparator(comma); } else { // How could this scenario arise? If it does, just expand the if-condition. Debug.Assert(CurrentToken.Kind != SyntaxKind.CommaToken); } } } // NOTE: nothing follows a cref parameter list, so there's no reason to recover here. // Just let the cref-level recovery code handle any remaining tokens. SyntaxToken close = EatToken(closeKind); return useSquareBrackets ? (BaseCrefParameterListSyntax)SyntaxFactory.CrefBracketedParameterList(open, list, close) : SyntaxFactory.CrefParameterList(open, list, close); } finally { _pool.Free(list); } } /// <summary> /// True if the current token could be the beginning of a cref parameter. /// </summary> private bool IsPossibleCrefParameter() { SyntaxKind kind = this.CurrentToken.Kind; switch (kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: case SyntaxKind.IdentifierToken: return true; default: return SyntaxFacts.IsPredefinedType(kind); } } /// <summary> /// Parse an element of a cref parameter list. /// </summary> /// <remarks> /// "ref" and "out" work, but "params", "this", and "__arglist" don't. /// </remarks> private CrefParameterSyntax ParseCrefParameter() { SyntaxToken refKindOpt = null; switch (CurrentToken.Kind) { case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: refKindOpt = EatToken(); break; } TypeSyntax type = ParseCrefType(typeArgumentsMustBeIdentifiers: false); return SyntaxFactory.CrefParameter(refKindOpt, type); } /// <summary> /// Parse an identifier, optionally followed by an angle-bracketed list of type parameters. /// </summary> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> private SimpleNameSyntax ParseCrefName(bool typeArgumentsMustBeIdentifiers) { SyntaxToken identifierToken = EatToken(SyntaxKind.IdentifierToken); if (CurrentToken.Kind != SyntaxKind.LessThanToken) { return SyntaxFactory.IdentifierName(identifierToken); } var open = EatToken(); var list = _pool.AllocateSeparated<TypeSyntax>(); try { while (true) { TypeSyntax typeSyntax = ParseCrefType(typeArgumentsMustBeIdentifiers); if (typeArgumentsMustBeIdentifiers && typeSyntax.Kind != SyntaxKind.IdentifierName) { typeSyntax = this.AddError(typeSyntax, ErrorCode.WRN_ErrorOverride, new SyntaxDiagnosticInfo(ErrorCode.ERR_TypeParamMustBeIdentifier), $"{(int)ErrorCode.ERR_TypeParamMustBeIdentifier:d4}"); } list.Add(typeSyntax); var currentKind = CurrentToken.Kind; if (currentKind == SyntaxKind.CommaToken || currentKind == SyntaxKind.IdentifierToken || SyntaxFacts.IsPredefinedType(CurrentToken.Kind)) { // NOTE: if the current token is an identifier or predefined type, then we're // actually inserting a missing commas. list.AddSeparator(EatToken(SyntaxKind.CommaToken)); } else { break; } } SyntaxToken close = EatToken(SyntaxKind.GreaterThanToken); open = CheckFeatureAvailability(open, MessageID.IDS_FeatureGenerics, forceWarning: true); return SyntaxFactory.GenericName(identifierToken, SyntaxFactory.TypeArgumentList(open, list, close)); } finally { _pool.Free(list); } } /// <summary> /// Parse a type. May include an alias, a predefined type, and/or a qualified name. /// </summary> /// <remarks> /// Pointer, nullable, or array types are only allowed if <paramref name="typeArgumentsMustBeIdentifiers"/> is false. /// Leaves a dot and a name unconsumed if the name is not followed by another dot /// and checkForMember is true. /// </remarks> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> /// <param name="checkForMember">True means that the last name should not be consumed /// if it is followed by a parameter list.</param> private TypeSyntax ParseCrefType(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) { TypeSyntax typeWithoutSuffix = ParseCrefTypeHelper(typeArgumentsMustBeIdentifiers, checkForMember); return typeArgumentsMustBeIdentifiers ? typeWithoutSuffix : ParseCrefTypeSuffix(typeWithoutSuffix); } /// <summary> /// Parse a type. May include an alias, a predefined type, and/or a qualified name. /// </summary> /// <remarks> /// No pointer, nullable, or array types. /// Leaves a dot and a name unconsumed if the name is not followed by another dot /// and checkForMember is true. /// </remarks> /// <param name="typeArgumentsMustBeIdentifiers">True to give an error when a non-identifier /// type argument is seen, false to accept. No change in the shape of the tree.</param> /// <param name="checkForMember">True means that the last name should not be consumed /// if it is followed by a parameter list.</param> private TypeSyntax ParseCrefTypeHelper(bool typeArgumentsMustBeIdentifiers, bool checkForMember = false) { NameSyntax leftName; if (SyntaxFacts.IsPredefinedType(CurrentToken.Kind)) { // e.g. "int" // NOTE: a predefined type will not fit into a NameSyntax, so we'll return // immediately. The upshot is that you can only dot into a predefined type // once (e.g. not "int.A.B"), which is fine because we know that none of them // have nested types. return SyntaxFactory.PredefinedType(EatToken()); } else if (CurrentToken.Kind == SyntaxKind.IdentifierToken && PeekToken(1).Kind == SyntaxKind.ColonColonToken) { // e.g. "A::B" SyntaxToken alias = EatToken(); if (alias.ContextualKind == SyntaxKind.GlobalKeyword) { alias = ConvertToKeyword(alias); } alias = CheckFeatureAvailability(alias, MessageID.IDS_FeatureGlobalNamespace, forceWarning: true); SyntaxToken colonColon = EatToken(); SimpleNameSyntax name = ParseCrefName(typeArgumentsMustBeIdentifiers); leftName = SyntaxFactory.AliasQualifiedName(SyntaxFactory.IdentifierName(alias), colonColon, name); } else { // e.g. "A" ResetPoint resetPoint = GetResetPoint(); leftName = ParseCrefName(typeArgumentsMustBeIdentifiers); if (checkForMember && (leftName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken)) { // If this isn't the first part of a dotted name, then we prefer to represent it // as a MemberCrefSyntax. this.Reset(ref resetPoint); this.Release(ref resetPoint); return null; } this.Release(ref resetPoint); } while (CurrentToken.Kind == SyntaxKind.DotToken) { // NOTE: we make a lot of these, but we'll reset, at most, one time. ResetPoint resetPoint = GetResetPoint(); SyntaxToken dot = EatToken(); SimpleNameSyntax rightName = ParseCrefName(typeArgumentsMustBeIdentifiers); if (checkForMember && (rightName.IsMissing || CurrentToken.Kind != SyntaxKind.DotToken)) { this.Reset(ref resetPoint); // Go back to before the dot - it must have been the trailing dot. this.Release(ref resetPoint); return leftName; } this.Release(ref resetPoint); leftName = SyntaxFactory.QualifiedName(leftName, dot, rightName); } return leftName; } /// <summary> /// Once the name part of a type (including type parameter/argument lists) is parsed, /// we need to consume ?, *, and rank specifiers. /// </summary> private TypeSyntax ParseCrefTypeSuffix(TypeSyntax type) { if (CurrentToken.Kind == SyntaxKind.QuestionToken) { type = SyntaxFactory.NullableType(type, EatToken()); } while (CurrentToken.Kind == SyntaxKind.AsteriskToken) { type = SyntaxFactory.PointerType(type, EatToken()); } if (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { var omittedArraySizeExpressionInstance = SyntaxFactory.OmittedArraySizeExpression(SyntaxFactory.Token(SyntaxKind.OmittedArraySizeExpressionToken)); var rankList = _pool.Allocate<ArrayRankSpecifierSyntax>(); try { while (CurrentToken.Kind == SyntaxKind.OpenBracketToken) { SyntaxToken open = EatToken(); var dimensionList = _pool.AllocateSeparated<ExpressionSyntax>(); try { while (this.CurrentToken.Kind != SyntaxKind.CloseBracketToken) { if (this.CurrentToken.Kind == SyntaxKind.CommaToken) { // NOTE: trivia will be attached to comma, not omitted array size dimensionList.Add(omittedArraySizeExpressionInstance); dimensionList.AddSeparator(this.EatToken()); } else { // CONSIDER: if we expect people to try to put expressions in between // the commas, then it might be more reasonable to recover by skipping // tokens until we hit a CloseBracketToken (or some other terminator). break; } } // Don't end on a comma. // If the omitted size would be the only element, then skip it unless sizes were expected. if ((dimensionList.Count & 1) == 0) { dimensionList.Add(omittedArraySizeExpressionInstance); } // Eat the close brace and we're done. var close = this.EatToken(SyntaxKind.CloseBracketToken); rankList.Add(SyntaxFactory.ArrayRankSpecifier(open, dimensionList, close)); } finally { _pool.Free(dimensionList); } } type = SyntaxFactory.ArrayType(type, rankList); } finally { _pool.Free(rankList); } } return type; } /// <summary> /// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment. /// </summary> private bool IsEndOfCrefAttribute { get { switch (CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: return (this.Mode & LexerMode.XmlCrefQuote) == LexerMode.XmlCrefQuote; case SyntaxKind.DoubleQuoteToken: return (this.Mode & LexerMode.XmlCrefDoubleQuote) == LexerMode.XmlCrefDoubleQuote; case SyntaxKind.EndOfFileToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; case SyntaxKind.BadToken: // If it's a real '<' (not &lt;, etc), then we assume it's the beginning // of the next XML element. return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) || IsNonAsciiQuotationMark(CurrentToken); default: return false; } } } /// <summary> /// Convenience method for checking the mode. /// </summary> private bool InCref { get { switch (this.Mode & (LexerMode.XmlCrefDoubleQuote | LexerMode.XmlCrefQuote)) { case LexerMode.XmlCrefQuote: case LexerMode.XmlCrefDoubleQuote: return true; default: return false; } } } #endregion Cref #region Name attribute values private IdentifierNameSyntax ParseNameAttributeValue() { // Never report a parse error - just fail to bind the name later on. SyntaxToken identifierToken = this.EatToken(SyntaxKind.IdentifierToken, reportError: false); if (!IsEndOfNameAttribute) { var badTokens = _pool.Allocate<SyntaxToken>(); while (!IsEndOfNameAttribute) { badTokens.Add(this.EatToken()); } identifierToken = AddTrailingSkippedSyntax(identifierToken, badTokens.ToListNode()); _pool.Free(badTokens); } return SyntaxFactory.IdentifierName(identifierToken); } /// <summary> /// Ends at appropriate quotation mark, EOF, or EndOfDocumentationComment. /// </summary> private bool IsEndOfNameAttribute { get { switch (CurrentToken.Kind) { case SyntaxKind.SingleQuoteToken: return (this.Mode & LexerMode.XmlNameQuote) == LexerMode.XmlNameQuote; case SyntaxKind.DoubleQuoteToken: return (this.Mode & LexerMode.XmlNameDoubleQuote) == LexerMode.XmlNameDoubleQuote; case SyntaxKind.EndOfFileToken: case SyntaxKind.EndOfDocumentationCommentToken: return true; case SyntaxKind.BadToken: // If it's a real '<' (not &lt;, etc), then we assume it's the beginning // of the next XML element. return CurrentToken.Text == SyntaxFacts.GetText(SyntaxKind.LessThanToken) || IsNonAsciiQuotationMark(CurrentToken); default: return false; } } } #endregion Name attribute values } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/EditorConfigStorageLocation`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Specifies that an option should be read from an .editorconfig file. /// </summary> internal sealed class EditorConfigStorageLocation<T> : OptionStorageLocation2, IEditorConfigStorageLocation2 { public string KeyName { get; } private readonly Func<string, Type, Optional<T>> _parseValue; private readonly Func<T, OptionSet, string?> _getEditorConfigStringForValue; public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(value)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<OptionSet, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(optionSet)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, OptionSet, string> getEditorConfigStringForValue) { if (parseValue == null) { throw new ArgumentNullException(nameof(parseValue)); } KeyName = keyName ?? throw new ArgumentNullException(nameof(keyName)); // If we're explicitly given a parsing function we can throw away the type when parsing _parseValue = (s, type) => parseValue(s); _getEditorConfigStringForValue = getEditorConfigStringForValue ?? throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? result) { if (rawOptions.TryGetValue(KeyName, out var value) && value is object) { var ret = TryGetOption(value, type, out var typedResult); result = typedResult; return ret; } result = null; return false; } internal bool TryGetOption(string value, Type type, [MaybeNullWhen(false)] out T result) { var optionalValue = _parseValue(value, type); if (optionalValue.HasValue) { result = optionalValue.Value; return result != null; } else { result = default!; return false; } } /// <summary> /// Gets the editorconfig string representation for this storage location. /// </summary> public string GetEditorConfigStringValue(T value, OptionSet optionSet) { var editorConfigStringForValue = _getEditorConfigStringForValue(value, optionSet); RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(editorConfigStringForValue)); Debug.Assert(editorConfigStringForValue.All(ch => !(char.IsWhiteSpace(ch) || char.IsUpper(ch)))); return editorConfigStringForValue; } string IEditorConfigStorageLocation2.GetEditorConfigString(object? value, OptionSet optionSet) => $"{KeyName} = {((IEditorConfigStorageLocation2)this).GetEditorConfigStringValue(value, optionSet)}"; string IEditorConfigStorageLocation2.GetEditorConfigStringValue(object? value, OptionSet optionSet) { T typedValue; if (value is ICodeStyleOption codeStyleOption) { typedValue = (T)codeStyleOption.AsCodeStyleOption<T>(); } else { typedValue = (T)value!; } return GetEditorConfigStringValue(typedValue, optionSet); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Specifies that an option should be read from an .editorconfig file. /// </summary> internal sealed class EditorConfigStorageLocation<T> : OptionStorageLocation2, IEditorConfigStorageLocation2 { public string KeyName { get; } private readonly Func<string, Type, Optional<T>> _parseValue; private readonly Func<T, OptionSet, string?> _getEditorConfigStringForValue; public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(value)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<OptionSet, string> getEditorConfigStringForValue) : this(keyName, parseValue, (value, optionSet) => getEditorConfigStringForValue(optionSet)) { if (getEditorConfigStringForValue == null) { throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } } public EditorConfigStorageLocation(string keyName, Func<string, Optional<T>> parseValue, Func<T, OptionSet, string> getEditorConfigStringForValue) { if (parseValue == null) { throw new ArgumentNullException(nameof(parseValue)); } KeyName = keyName ?? throw new ArgumentNullException(nameof(keyName)); // If we're explicitly given a parsing function we can throw away the type when parsing _parseValue = (s, type) => parseValue(s); _getEditorConfigStringForValue = getEditorConfigStringForValue ?? throw new ArgumentNullException(nameof(getEditorConfigStringForValue)); } public bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? result) { if (rawOptions.TryGetValue(KeyName, out var value) && value is object) { var ret = TryGetOption(value, type, out var typedResult); result = typedResult; return ret; } result = null; return false; } internal bool TryGetOption(string value, Type type, [MaybeNullWhen(false)] out T result) { var optionalValue = _parseValue(value, type); if (optionalValue.HasValue) { result = optionalValue.Value; return result != null; } else { result = default!; return false; } } /// <summary> /// Gets the editorconfig string representation for this storage location. /// </summary> public string GetEditorConfigStringValue(T value, OptionSet optionSet) { var editorConfigStringForValue = _getEditorConfigStringForValue(value, optionSet); RoslynDebug.Assert(!RoslynString.IsNullOrEmpty(editorConfigStringForValue)); Debug.Assert(editorConfigStringForValue.All(ch => !(char.IsWhiteSpace(ch) || char.IsUpper(ch)))); return editorConfigStringForValue; } string IEditorConfigStorageLocation2.GetEditorConfigString(object? value, OptionSet optionSet) => $"{KeyName} = {((IEditorConfigStorageLocation2)this).GetEditorConfigStringValue(value, optionSet)}"; string IEditorConfigStorageLocation2.GetEditorConfigStringValue(object? value, OptionSet optionSet) { T typedValue; if (value is ICodeStyleOption codeStyleOption) { typedValue = (T)codeStyleOption.AsCodeStyleOption<T>(); } else { typedValue = (T)value!; } return GetEditorConfigStringValue(typedValue, optionSet); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/CSharpTest2/Recommendations/RemoveKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RemoveKeywordRecommenderTests : 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 TestAfterEvent() { await VerifyKeywordAsync( @"class C { event Goo Bar { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAdd() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddAndAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddBlock() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveKeyword() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveAccessor() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RemoveKeywordRecommenderTests : 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 TestAfterEvent() { await VerifyKeywordAsync( @"class C { event Goo Bar { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAdd() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddAndAttribute() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } [Bar] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAddBlock() { await VerifyKeywordAsync( @"class C { event Goo Bar { add { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveKeyword() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRemoveAccessor() { await VerifyAbsenceAsync( @"class C { event Goo Bar { remove { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInProperty() { await VerifyAbsenceAsync( @"class C { int Goo { $$"); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeEnum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed partial class CodeEnum : AbstractCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeEnum(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeEnum CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeEnum(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnumMember(LookupNode(), name, value, position); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE.CodeEnum))] public sealed partial class CodeEnum : AbstractCodeType, EnvDTE.CodeEnum { internal static EnvDTE.CodeEnum Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeEnum(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static EnvDTE.CodeEnum CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeEnum(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeEnum)ComAggregate.CreateAggregatedObject(element); } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeEnum( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementEnum; } } public EnvDTE.CodeVariable AddMember(string name, object value, object position) { return FileCodeModel.EnsureEditor(() => { return FileCodeModel.AddEnumMember(LookupNode(), name, value, position); }); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateComparisonOperators Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateComparisonOperators Public Class GenerateComparisonOperatorsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New GenerateComparisonOperatorsCodeRefactoringProvider() End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestClass() As Task Await TestInRegularAndScript1Async( " imports System [||]class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestExplicitImpl() As Task Await TestInRegularAndScript1Async( " imports System [||]class C implements IComparable(Of C) private function CompareToImpl(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) private function CompareToImpl(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestOnInterface() As Task Await TestInRegularAndScript1Async( " imports System class C implements [||]IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestAtEndOfInterface() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C)[||] public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestInBody() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function [||] end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithoutCompareMethod() As Task Await TestMissingAsync( " imports System class C implements IComparable(Of C) [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithUnknownType() As Task Await TestMissingAsync( " imports System class C : IComparable<Goo> public int CompareTo(Goo g) => 0 [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithAllExistingOperators() As Task Await TestMissingAsync( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestWithExistingOperator() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator [||] end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMultipleInterfaces() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C), IComparable(of integer) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function public function CompareTo(c as integer) as integer implements IComparable(of integer).CompareTo Return 0 end function [||] end class", " imports System class C implements IComparable(Of C), IComparable(of integer) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function public function CompareTo(c as integer) as integer implements IComparable(of integer).CompareTo Return 0 end function Public Shared Operator >(left As C, right As Integer) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As Integer) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As Integer) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As Integer) As Boolean Return left.CompareTo(right) <= 0 End Operator end class", index:=1) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.GenerateComparisonOperators Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.GenerateComparisonOperators Public Class GenerateComparisonOperatorsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New GenerateComparisonOperatorsCodeRefactoringProvider() End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestClass() As Task Await TestInRegularAndScript1Async( " imports System [||]class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestExplicitImpl() As Task Await TestInRegularAndScript1Async( " imports System [||]class C implements IComparable(Of C) private function CompareToImpl(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) private function CompareToImpl(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return DirectCast(left, IComparable(Of C)).CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestOnInterface() As Task Await TestInRegularAndScript1Async( " imports System class C implements [||]IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestAtEndOfInterface() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C)[||] public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestInBody() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function [||] end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithoutCompareMethod() As Task Await TestMissingAsync( " imports System class C implements IComparable(Of C) [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithUnknownType() As Task Await TestMissingAsync( " imports System class C : IComparable<Goo> public int CompareTo(Goo g) => 0 [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMissingWithAllExistingOperators() As Task Await TestMissingAsync( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator [||] end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestWithExistingOperator() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator [||] end class", " imports System class C implements IComparable(Of C) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function Public Shared Operator >(left As C, right As C) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As C) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As C) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As C) As Boolean Return left.CompareTo(right) <= 0 End Operator end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)> Public Async Function TestMultipleInterfaces() As Task Await TestInRegularAndScript1Async( " imports System class C implements IComparable(Of C), IComparable(of integer) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function public function CompareTo(c as integer) as integer implements IComparable(of integer).CompareTo Return 0 end function [||] end class", " imports System class C implements IComparable(Of C), IComparable(of integer) public function CompareTo(c as C) as integer implements IComparable(of C).CompareTo Return 0 end function public function CompareTo(c as integer) as integer implements IComparable(of integer).CompareTo Return 0 end function Public Shared Operator >(left As C, right As Integer) As Boolean Return left.CompareTo(right) > 0 End Operator Public Shared Operator <(left As C, right As Integer) As Boolean Return left.CompareTo(right) < 0 End Operator Public Shared Operator >=(left As C, right As Integer) As Boolean Return left.CompareTo(right) >= 0 End Operator Public Shared Operator <=(left As C, right As Integer) As Boolean Return left.CompareTo(right) <= 0 End Operator end class", index:=1) End Function End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/CSharp/Portable/Structure/Providers/SwitchStatementStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, SwitchStatementSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds((node.CloseParenToken != default) ? node.CloseParenToken.Span.End : node.Expression.Span.End, node.CloseBraceToken.Span.End), hintSpan: node.Span, type: BlockTypes.Conditional)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, SwitchStatementSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds((node.CloseParenToken != default) ? node.CloseParenToken.Span.End : node.Expression.Span.End, node.CloseBraceToken.Span.End), hintSpan: node.Span, type: BlockTypes.Conditional)); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/BuildBoss/PackageReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct PackageReference { internal string Name { get; } internal string Version { get; } internal PackageReference(string name, string version) { Name = name; Version = version; } public override string ToString() => $"{Name} - {Version}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace BuildBoss { internal struct PackageReference { internal string Name { get; } internal string Version { get; } internal PackageReference(string name, string version) { Name = name; Version = version; } public override string ToString() => $"{Name} - {Version}"; } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Interop/IAnalyzerHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("9A37496A-F2CB-49A8-A684-7DEAAD2B0F07")] internal interface IAnalyzerHost { void AddAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void RemoveAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void SetRuleSetFile([MarshalAs(UnmanagedType.LPWStr)] string ruleSetFileFullPath); void AddAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); void RemoveAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("9A37496A-F2CB-49A8-A684-7DEAAD2B0F07")] internal interface IAnalyzerHost { void AddAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void RemoveAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void SetRuleSetFile([MarshalAs(UnmanagedType.LPWStr)] string ruleSetFileFullPath); void AddAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); void RemoveAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Tools/ExternalAccess/FSharp/Internal/GoToDefinition/FSharpFindDefinitionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared] internal class FSharpFindDefinitionService : IFindDefinitionService { private readonly IFSharpFindDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpFindDefinitionService(IFSharpFindDefinitionService service) { _service = service; } public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.GoToDefinition; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Navigation; using Microsoft.CodeAnalysis.GoToDefinition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.GoToDefinition { [ExportLanguageService(typeof(IFindDefinitionService), LanguageNames.FSharp), Shared] internal class FSharpFindDefinitionService : IFindDefinitionService { private readonly IFSharpFindDefinitionService _service; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpFindDefinitionService(IFSharpFindDefinitionService service) { _service = service; } public async Task<ImmutableArray<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken) { var items = await _service.FindDefinitionsAsync(document, position, cancellationToken).ConfigureAwait(false); return items.SelectAsArray(x => (INavigableItem)new InternalFSharpNavigableItem(x)); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/CSharp/Portable/Workspace/LanguageServices/CSharpSyntaxTreeFactoryService.RecoverableSyntaxTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax tree that only has a weak reference to its /// underlying data. This way it can be passed around without forcing /// the underlying full tree to stay alive. Think of it more as a /// key that can be used to identify a tree rather than the tree itself. /// </summary> internal sealed class RecoverableSyntaxTree : CSharpSyntaxTree, IRecoverableSyntaxTree<CompilationUnitSyntax>, ICachedObjectOwner { private readonly RecoverableSyntaxRoot<CompilationUnitSyntax> _recoverableRoot; private readonly SyntaxTreeInfo _info; private readonly IProjectCacheHostService _projectCacheService; private readonly ProjectId _cacheKey; object ICachedObjectOwner.CachedObject { get; set; } private RecoverableSyntaxTree(AbstractSyntaxTreeFactoryService service, ProjectId cacheKey, CompilationUnitSyntax root, SyntaxTreeInfo info) { _recoverableRoot = new RecoverableSyntaxRoot<CompilationUnitSyntax>(service, root, this); _info = info; _projectCacheService = service.LanguageServices.WorkspaceServices.GetService<IProjectCacheHostService>(); _cacheKey = cacheKey; } private RecoverableSyntaxTree(RecoverableSyntaxTree original, SyntaxTreeInfo info) { _recoverableRoot = original._recoverableRoot.WithSyntaxTree(this); _info = info; _projectCacheService = original._projectCacheService; _cacheKey = original._cacheKey; } internal static SyntaxTree CreateRecoverableTree( AbstractSyntaxTreeFactoryService service, ProjectId cacheKey, string filePath, ParseOptions options, ValueSource<TextAndVersion> text, Encoding encoding, CompilationUnitSyntax root) { return new RecoverableSyntaxTree( service, cacheKey, root, new SyntaxTreeInfo( filePath, options, text, encoding, root.FullSpan.Length)); } public override string FilePath { get { return _info.FilePath; } } public override CSharpParseOptions Options { get { return (CSharpParseOptions)_info.Options; } } public override int Length { get { return _info.Length; } } public override bool TryGetText(out SourceText text) => _info.TryGetText(out text); public override SourceText GetText(CancellationToken cancellationToken) => _info.TextSource.GetValue(cancellationToken).Text; public override Task<SourceText> GetTextAsync(CancellationToken cancellationToken) => _info.GetTextAsync(cancellationToken); public override Encoding Encoding { get { return _info.Encoding; } } private CompilationUnitSyntax CacheRootNode(CompilationUnitSyntax node) => _projectCacheService.CacheObjectIfCachingEnabledForKey(_cacheKey, this, node); public override bool TryGetRoot(out CSharpSyntaxNode root) { var status = _recoverableRoot.TryGetValue(out var node); root = node; CacheRootNode(node); return status; } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default) => CacheRootNode(_recoverableRoot.GetValue(cancellationToken)); public override async Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken) => CacheRootNode(await _recoverableRoot.GetValueAsync(cancellationToken).ConfigureAwait(false)); public override bool HasCompilationUnitRoot { get { return true; } } public override SyntaxReference GetReference(SyntaxNode node) { if (node != null) { // many people will take references to nodes in this tree. // We don't actually want those references to keep the tree alive. if (node.Span.Length == 0) { return new PathSyntaxReference(node); } else { return new PositionalSyntaxReference(node); } } else { return new NullSyntaxReference(this); } } CompilationUnitSyntax IRecoverableSyntaxTree<CompilationUnitSyntax>.CloneNodeAsRoot(CompilationUnitSyntax root) => CloneNodeAsRoot(root); public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_info.Options, options) && this.TryGetRoot(out var oldRoot) && ReferenceEquals(root, oldRoot)) { return this; } return Create((CSharpSyntaxNode)root, this.Options, _info.FilePath); } public override SyntaxTree WithFilePath(string path) { if (path == this.FilePath) { return this; } return new RecoverableSyntaxTree(this, _info.WithFilePath(path)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class CSharpSyntaxTreeFactoryServiceFactory { private partial class CSharpSyntaxTreeFactoryService { /// <summary> /// Represents a syntax tree that only has a weak reference to its /// underlying data. This way it can be passed around without forcing /// the underlying full tree to stay alive. Think of it more as a /// key that can be used to identify a tree rather than the tree itself. /// </summary> internal sealed class RecoverableSyntaxTree : CSharpSyntaxTree, IRecoverableSyntaxTree<CompilationUnitSyntax>, ICachedObjectOwner { private readonly RecoverableSyntaxRoot<CompilationUnitSyntax> _recoverableRoot; private readonly SyntaxTreeInfo _info; private readonly IProjectCacheHostService _projectCacheService; private readonly ProjectId _cacheKey; object ICachedObjectOwner.CachedObject { get; set; } private RecoverableSyntaxTree(AbstractSyntaxTreeFactoryService service, ProjectId cacheKey, CompilationUnitSyntax root, SyntaxTreeInfo info) { _recoverableRoot = new RecoverableSyntaxRoot<CompilationUnitSyntax>(service, root, this); _info = info; _projectCacheService = service.LanguageServices.WorkspaceServices.GetService<IProjectCacheHostService>(); _cacheKey = cacheKey; } private RecoverableSyntaxTree(RecoverableSyntaxTree original, SyntaxTreeInfo info) { _recoverableRoot = original._recoverableRoot.WithSyntaxTree(this); _info = info; _projectCacheService = original._projectCacheService; _cacheKey = original._cacheKey; } internal static SyntaxTree CreateRecoverableTree( AbstractSyntaxTreeFactoryService service, ProjectId cacheKey, string filePath, ParseOptions options, ValueSource<TextAndVersion> text, Encoding encoding, CompilationUnitSyntax root) { return new RecoverableSyntaxTree( service, cacheKey, root, new SyntaxTreeInfo( filePath, options, text, encoding, root.FullSpan.Length)); } public override string FilePath { get { return _info.FilePath; } } public override CSharpParseOptions Options { get { return (CSharpParseOptions)_info.Options; } } public override int Length { get { return _info.Length; } } public override bool TryGetText(out SourceText text) => _info.TryGetText(out text); public override SourceText GetText(CancellationToken cancellationToken) => _info.TextSource.GetValue(cancellationToken).Text; public override Task<SourceText> GetTextAsync(CancellationToken cancellationToken) => _info.GetTextAsync(cancellationToken); public override Encoding Encoding { get { return _info.Encoding; } } private CompilationUnitSyntax CacheRootNode(CompilationUnitSyntax node) => _projectCacheService.CacheObjectIfCachingEnabledForKey(_cacheKey, this, node); public override bool TryGetRoot(out CSharpSyntaxNode root) { var status = _recoverableRoot.TryGetValue(out var node); root = node; CacheRootNode(node); return status; } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default) => CacheRootNode(_recoverableRoot.GetValue(cancellationToken)); public override async Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken) => CacheRootNode(await _recoverableRoot.GetValueAsync(cancellationToken).ConfigureAwait(false)); public override bool HasCompilationUnitRoot { get { return true; } } public override SyntaxReference GetReference(SyntaxNode node) { if (node != null) { // many people will take references to nodes in this tree. // We don't actually want those references to keep the tree alive. if (node.Span.Length == 0) { return new PathSyntaxReference(node); } else { return new PositionalSyntaxReference(node); } } else { return new NullSyntaxReference(this); } } CompilationUnitSyntax IRecoverableSyntaxTree<CompilationUnitSyntax>.CloneNodeAsRoot(CompilationUnitSyntax root) => CloneNodeAsRoot(root); public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { if (ReferenceEquals(_info.Options, options) && this.TryGetRoot(out var oldRoot) && ReferenceEquals(root, oldRoot)) { return this; } return Create((CSharpSyntaxNode)root, this.Options, _info.FilePath); } public override SyntaxTree WithFilePath(string path) { if (path == this.FilePath) { return this; } return new RecoverableSyntaxTree(this, _info.WithFilePath(path)); } } } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Core/Portable/Symbols/Attributes/DecodeWellKnownAttributeArguments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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> /// Contains common arguments to Symbol.DecodeWellKnownAttribute method in both the language compilers. /// </summary> internal struct DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData { /// <summary> /// Object to store the decoded data from bound well-known attributes. /// Created lazily only when some decoded data needs to be stored, null otherwise. /// </summary> private WellKnownAttributeData? _lazyDecodeData; /// <summary> /// Gets or creates the decoded data object. /// </summary> /// <remarks> /// This method must be called only when some decoded data will be stored into it subsequently. /// </remarks> public T GetOrCreateData<T>() where T : WellKnownAttributeData, new() { if (_lazyDecodeData == null) { _lazyDecodeData = new T(); } return (T)_lazyDecodeData; } /// <summary> /// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>. /// </summary> public readonly bool HasDecodedData { get { if (_lazyDecodeData != null) { _lazyDecodeData.VerifyDataStored(expected: true); return true; } return false; } } /// <summary> /// Gets the stored decoded data. /// </summary> /// <remarks> /// Assumes <see cref="HasDecodedData"/> is true. /// </remarks> public readonly WellKnownAttributeData DecodedData { get { Debug.Assert(this.HasDecodedData); return _lazyDecodeData!; } } /// <summary> /// Syntax of the attribute to decode. Might be null when the attribute information is not coming /// from syntax. For example, an assembly attribute propagated from added module to the resulting assembly. /// </summary> public TAttributeSyntax? AttributeSyntaxOpt { get; set; } /// <summary> /// Bound attribute to decode. /// </summary> public TAttributeData Attribute { get; set; } /// <summary> /// The index of the attribute in the list of attributes to decode. /// </summary> public int Index { get; set; } /// <summary> /// Total count of attributes to decode. /// </summary> public int AttributesCount { get; set; } /// <summary> /// Diagnostic bag. /// </summary> public BindingDiagnosticBag Diagnostics { get; set; } /// <summary> /// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself. /// Used e.g. for return type attributes of a method symbol. /// </summary> public TAttributeLocation SymbolPart { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Contains common arguments to Symbol.DecodeWellKnownAttribute method in both the language compilers. /// </summary> internal struct DecodeWellKnownAttributeArguments<TAttributeSyntax, TAttributeData, TAttributeLocation> where TAttributeSyntax : SyntaxNode where TAttributeData : AttributeData { /// <summary> /// Object to store the decoded data from bound well-known attributes. /// Created lazily only when some decoded data needs to be stored, null otherwise. /// </summary> private WellKnownAttributeData? _lazyDecodeData; /// <summary> /// Gets or creates the decoded data object. /// </summary> /// <remarks> /// This method must be called only when some decoded data will be stored into it subsequently. /// </remarks> public T GetOrCreateData<T>() where T : WellKnownAttributeData, new() { if (_lazyDecodeData == null) { _lazyDecodeData = new T(); } return (T)_lazyDecodeData; } /// <summary> /// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>. /// </summary> public readonly bool HasDecodedData { get { if (_lazyDecodeData != null) { _lazyDecodeData.VerifyDataStored(expected: true); return true; } return false; } } /// <summary> /// Gets the stored decoded data. /// </summary> /// <remarks> /// Assumes <see cref="HasDecodedData"/> is true. /// </remarks> public readonly WellKnownAttributeData DecodedData { get { Debug.Assert(this.HasDecodedData); return _lazyDecodeData!; } } /// <summary> /// Syntax of the attribute to decode. Might be null when the attribute information is not coming /// from syntax. For example, an assembly attribute propagated from added module to the resulting assembly. /// </summary> public TAttributeSyntax? AttributeSyntaxOpt { get; set; } /// <summary> /// Bound attribute to decode. /// </summary> public TAttributeData Attribute { get; set; } /// <summary> /// The index of the attribute in the list of attributes to decode. /// </summary> public int Index { get; set; } /// <summary> /// Total count of attributes to decode. /// </summary> public int AttributesCount { get; set; } /// <summary> /// Diagnostic bag. /// </summary> public BindingDiagnosticBag Diagnostics { get; set; } /// <summary> /// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself. /// Used e.g. for return type attributes of a method symbol. /// </summary> public TAttributeLocation SymbolPart { get; set; } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptEditorInlineRenameService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { /// <summary> /// Language service that allows a language to participate in the editor's inline rename feature. /// </summary> internal interface IVSTypeScriptEditorInlineRenameService { Task<IVSTypeScriptInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { /// <summary> /// Language service that allows a language to participate in the editor's inline rename feature. /// </summary> internal interface IVSTypeScriptEditorInlineRenameService { Task<IVSTypeScriptInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService { public abstract Guid LanguageServiceId { get; } public abstract IServiceProvider SystemServiceProvider { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService { public abstract Guid LanguageServiceId { get; } public abstract IServiceProvider SystemServiceProvider { get; } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Semantics/StatementSyntaxWalker.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 ''' <summary> ''' This class walks all the statements in some syntax, in order, except those statements that are contained ''' inside expressions (a statement can occur inside an expression if it is inside ''' a lambda.) ''' ''' This is used when collecting the declarations and declaration spaces of a method body. ''' ''' Typically the client overrides this class and overrides various Visit methods, being sure to always ''' delegate back to the base. ''' </summary> Friend Class StatementSyntaxWalker Inherits VisualBasicSyntaxVisitor Public Overridable Sub VisitList(list As IEnumerable(Of VisualBasicSyntaxNode)) For Each n In list Visit(n) Next End Sub Public Overrides Sub VisitCompilationUnit(node As CompilationUnitSyntax) VisitList(node.Options) VisitList(node.Imports) VisitList(node.Attributes) VisitList(node.Members) End Sub Public Overrides Sub VisitNamespaceBlock(node As NamespaceBlockSyntax) Visit(node.NamespaceStatement) VisitList(node.Members) Visit(node.EndNamespaceStatement) End Sub Public Overrides Sub VisitModuleBlock(ByVal node As ModuleBlockSyntax) Visit(node.BlockStatement) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitClassBlock(ByVal node As ClassBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Implements) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitStructureBlock(ByVal node As StructureBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Implements) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitEnumBlock(ByVal node As EnumBlockSyntax) Visit(node.EnumStatement) VisitList(node.Members) Visit(node.EndEnumStatement) End Sub Public Overrides Sub VisitMethodBlock(ByVal node As MethodBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitConstructorBlock(node As ConstructorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitOperatorBlock(node As OperatorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitAccessorBlock(node As AccessorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitPropertyBlock(ByVal node As PropertyBlockSyntax) Visit(node.PropertyStatement) VisitList(node.Accessors) Visit(node.EndPropertyStatement) End Sub Public Overrides Sub VisitEventBlock(ByVal node As EventBlockSyntax) Visit(node.EventStatement) VisitList(node.Accessors) Visit(node.EndEventStatement) End Sub Public Overrides Sub VisitWhileBlock(ByVal node As WhileBlockSyntax) Visit(node.WhileStatement) VisitList(node.Statements) Visit(node.EndWhileStatement) End Sub Public Overrides Sub VisitUsingBlock(ByVal node As UsingBlockSyntax) Visit(node.UsingStatement) VisitList(node.Statements) Visit(node.EndUsingStatement) End Sub Public Overrides Sub VisitSyncLockBlock(ByVal node As SyncLockBlockSyntax) Visit(node.SyncLockStatement) VisitList(node.Statements) Visit(node.EndSyncLockStatement) End Sub Public Overrides Sub VisitWithBlock(ByVal node As WithBlockSyntax) Visit(node.WithStatement) VisitList(node.Statements) Visit(node.EndWithStatement) End Sub Public Overrides Sub VisitSingleLineIfStatement(ByVal node As SingleLineIfStatementSyntax) VisitList(node.Statements) Visit(node.ElseClause) End Sub Public Overrides Sub VisitSingleLineElseClause(ByVal node As SingleLineElseClauseSyntax) VisitList(node.Statements) End Sub Public Overrides Sub VisitMultiLineIfBlock(ByVal node As MultiLineIfBlockSyntax) Visit(node.IfStatement) VisitList(node.Statements) VisitList(node.ElseIfBlocks) Visit(node.ElseBlock) Visit(node.EndIfStatement) End Sub Public Overrides Sub VisitElseIfBlock(ByVal node As ElseIfBlockSyntax) Visit(node.ElseIfStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitElseBlock(ByVal node As ElseBlockSyntax) Visit(node.ElseStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitTryBlock(ByVal node As TryBlockSyntax) Visit(node.TryStatement) VisitList(node.Statements) VisitList(node.CatchBlocks) Visit(node.FinallyBlock) Visit(node.EndTryStatement) End Sub Public Overrides Sub VisitCatchBlock(ByVal node As CatchBlockSyntax) Visit(node.CatchStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitFinallyBlock(ByVal node As FinallyBlockSyntax) Visit(node.FinallyStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitSelectBlock(ByVal node As SelectBlockSyntax) Visit(node.SelectStatement) VisitList(node.CaseBlocks) Visit(node.EndSelectStatement) End Sub Public Overrides Sub VisitCaseBlock(ByVal node As CaseBlockSyntax) Visit(node.CaseStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitDoLoopBlock(ByVal node As DoLoopBlockSyntax) Visit(node.DoStatement) VisitList(node.Statements) Visit(node.LoopStatement) End Sub Public Overrides Sub VisitForBlock(ByVal node As ForBlockSyntax) Visit(node.ForStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitForEachBlock(ByVal node As ForEachBlockSyntax) Visit(node.ForEachStatement) VisitList(node.Statements) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' This class walks all the statements in some syntax, in order, except those statements that are contained ''' inside expressions (a statement can occur inside an expression if it is inside ''' a lambda.) ''' ''' This is used when collecting the declarations and declaration spaces of a method body. ''' ''' Typically the client overrides this class and overrides various Visit methods, being sure to always ''' delegate back to the base. ''' </summary> Friend Class StatementSyntaxWalker Inherits VisualBasicSyntaxVisitor Public Overridable Sub VisitList(list As IEnumerable(Of VisualBasicSyntaxNode)) For Each n In list Visit(n) Next End Sub Public Overrides Sub VisitCompilationUnit(node As CompilationUnitSyntax) VisitList(node.Options) VisitList(node.Imports) VisitList(node.Attributes) VisitList(node.Members) End Sub Public Overrides Sub VisitNamespaceBlock(node As NamespaceBlockSyntax) Visit(node.NamespaceStatement) VisitList(node.Members) Visit(node.EndNamespaceStatement) End Sub Public Overrides Sub VisitModuleBlock(ByVal node As ModuleBlockSyntax) Visit(node.BlockStatement) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitClassBlock(ByVal node As ClassBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Implements) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitStructureBlock(ByVal node As StructureBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Implements) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax) Visit(node.BlockStatement) VisitList(node.Inherits) VisitList(node.Members) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitEnumBlock(ByVal node As EnumBlockSyntax) Visit(node.EnumStatement) VisitList(node.Members) Visit(node.EndEnumStatement) End Sub Public Overrides Sub VisitMethodBlock(ByVal node As MethodBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitConstructorBlock(node As ConstructorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitOperatorBlock(node As OperatorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitAccessorBlock(node As AccessorBlockSyntax) Visit(node.BlockStatement) VisitList(node.Statements) Visit(node.EndBlockStatement) End Sub Public Overrides Sub VisitPropertyBlock(ByVal node As PropertyBlockSyntax) Visit(node.PropertyStatement) VisitList(node.Accessors) Visit(node.EndPropertyStatement) End Sub Public Overrides Sub VisitEventBlock(ByVal node As EventBlockSyntax) Visit(node.EventStatement) VisitList(node.Accessors) Visit(node.EndEventStatement) End Sub Public Overrides Sub VisitWhileBlock(ByVal node As WhileBlockSyntax) Visit(node.WhileStatement) VisitList(node.Statements) Visit(node.EndWhileStatement) End Sub Public Overrides Sub VisitUsingBlock(ByVal node As UsingBlockSyntax) Visit(node.UsingStatement) VisitList(node.Statements) Visit(node.EndUsingStatement) End Sub Public Overrides Sub VisitSyncLockBlock(ByVal node As SyncLockBlockSyntax) Visit(node.SyncLockStatement) VisitList(node.Statements) Visit(node.EndSyncLockStatement) End Sub Public Overrides Sub VisitWithBlock(ByVal node As WithBlockSyntax) Visit(node.WithStatement) VisitList(node.Statements) Visit(node.EndWithStatement) End Sub Public Overrides Sub VisitSingleLineIfStatement(ByVal node As SingleLineIfStatementSyntax) VisitList(node.Statements) Visit(node.ElseClause) End Sub Public Overrides Sub VisitSingleLineElseClause(ByVal node As SingleLineElseClauseSyntax) VisitList(node.Statements) End Sub Public Overrides Sub VisitMultiLineIfBlock(ByVal node As MultiLineIfBlockSyntax) Visit(node.IfStatement) VisitList(node.Statements) VisitList(node.ElseIfBlocks) Visit(node.ElseBlock) Visit(node.EndIfStatement) End Sub Public Overrides Sub VisitElseIfBlock(ByVal node As ElseIfBlockSyntax) Visit(node.ElseIfStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitElseBlock(ByVal node As ElseBlockSyntax) Visit(node.ElseStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitTryBlock(ByVal node As TryBlockSyntax) Visit(node.TryStatement) VisitList(node.Statements) VisitList(node.CatchBlocks) Visit(node.FinallyBlock) Visit(node.EndTryStatement) End Sub Public Overrides Sub VisitCatchBlock(ByVal node As CatchBlockSyntax) Visit(node.CatchStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitFinallyBlock(ByVal node As FinallyBlockSyntax) Visit(node.FinallyStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitSelectBlock(ByVal node As SelectBlockSyntax) Visit(node.SelectStatement) VisitList(node.CaseBlocks) Visit(node.EndSelectStatement) End Sub Public Overrides Sub VisitCaseBlock(ByVal node As CaseBlockSyntax) Visit(node.CaseStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitDoLoopBlock(ByVal node As DoLoopBlockSyntax) Visit(node.DoStatement) VisitList(node.Statements) Visit(node.LoopStatement) End Sub Public Overrides Sub VisitForBlock(ByVal node As ForBlockSyntax) Visit(node.ForStatement) VisitList(node.Statements) End Sub Public Overrides Sub VisitForEachBlock(ByVal node As ForEachBlockSyntax) Visit(node.ForEachStatement) VisitList(node.Statements) End Sub End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Scripting/Core/ScriptCompiler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Scripting { internal abstract class ScriptCompiler { public abstract Compilation CreateSubmission(Script script); public abstract DiagnosticFormatter DiagnosticFormatter { get; } public abstract StringComparer IdentifierComparer { get; } public abstract SyntaxTree ParseSubmission(SourceText text, ParseOptions parseOptions, CancellationToken cancellationToken); public abstract bool IsCompleteSubmission(SyntaxTree tree); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Scripting { internal abstract class ScriptCompiler { public abstract Compilation CreateSubmission(Script script); public abstract DiagnosticFormatter DiagnosticFormatter { get; } public abstract StringComparer IdentifierComparer { get; } public abstract SyntaxTree ParseSubmission(SourceText text, ParseOptions parseOptions, CancellationToken cancellationToken); public abstract bool IsCompleteSubmission(SyntaxTree tree); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/SymbolSearch/SymbolSearchUpdateEngineFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Factory that will produce the <see cref="ISymbolSearchUpdateEngine"/>. The default /// implementation produces an engine that will run in-process. Implementations at /// other layers can behave differently (for example, running the engine out-of-process). /// </summary> /// <remarks> /// This returns an No-op engine on non-Windows OS, because the backing storage depends on Windows APIs. /// </remarks> internal static partial class SymbolSearchUpdateEngineFactory { public static async Task<ISymbolSearchUpdateEngine> CreateEngineAsync( Workspace workspace, ISymbolSearchLogService logService, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(workspace, cancellationToken).ConfigureAwait(false); if (client != null) { return new RemoteUpdateEngine(client, logService); } // Couldn't go out of proc. Just do everything inside the current process. return CreateEngineInProcess(); } /// <summary> /// This returns a No-op engine if called on non-Windows OS, because the backing storage depends on Windows APIs. /// </summary> public static ISymbolSearchUpdateEngine CreateEngineInProcess() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new SymbolSearchUpdateEngine() : (ISymbolSearchUpdateEngine)new NoOpUpdateEngine(); } private sealed class NoOpUpdateEngine : ISymbolSearchUpdateEngine { public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithAssemblyResult>.Empty); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithTypeResult>.Empty); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty); public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) => default; } private sealed class RemoteUpdateEngine : ISymbolSearchUpdateEngine { private readonly RemoteServiceConnection<IRemoteSymbolSearchUpdateService> _connection; public RemoteUpdateEngine(RemoteHostClient client, ISymbolSearchLogService logService) => _connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(logService); public void Dispose() => _connection.Dispose(); public async ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithTypeResult>>( (service, cancellationToken) => service.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithTypeResult>.Empty; } public async ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithAssemblyResult>>( (service, cancellationToken) => service.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithAssemblyResult>.Empty; } public async ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync( string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<ReferenceAssemblyWithTypeResult>>( (service, cancellationToken) => service.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty; } public async ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) { // logService parameter is ignored since it's already set on the connection as a callback _ = logService; _ = await _connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, sourceName, localSettingsDirectory, cancellationToken), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SymbolSearch { /// <summary> /// Factory that will produce the <see cref="ISymbolSearchUpdateEngine"/>. The default /// implementation produces an engine that will run in-process. Implementations at /// other layers can behave differently (for example, running the engine out-of-process). /// </summary> /// <remarks> /// This returns an No-op engine on non-Windows OS, because the backing storage depends on Windows APIs. /// </remarks> internal static partial class SymbolSearchUpdateEngineFactory { public static async Task<ISymbolSearchUpdateEngine> CreateEngineAsync( Workspace workspace, ISymbolSearchLogService logService, CancellationToken cancellationToken) { var client = await RemoteHostClient.TryGetClientAsync(workspace, cancellationToken).ConfigureAwait(false); if (client != null) { return new RemoteUpdateEngine(client, logService); } // Couldn't go out of proc. Just do everything inside the current process. return CreateEngineInProcess(); } /// <summary> /// This returns a No-op engine if called on non-Windows OS, because the backing storage depends on Windows APIs. /// </summary> public static ISymbolSearchUpdateEngine CreateEngineInProcess() { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new SymbolSearchUpdateEngine() : (ISymbolSearchUpdateEngine)new NoOpUpdateEngine(); } private sealed class NoOpUpdateEngine : ISymbolSearchUpdateEngine { public ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync(string source, string assemblyName, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithAssemblyResult>.Empty); public ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<PackageWithTypeResult>.Empty); public ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(string name, int arity, CancellationToken cancellationToken) => ValueTaskFactory.FromResult(ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty); public ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) => default; } private sealed class RemoteUpdateEngine : ISymbolSearchUpdateEngine { private readonly RemoteServiceConnection<IRemoteSymbolSearchUpdateService> _connection; public RemoteUpdateEngine(RemoteHostClient client, ISymbolSearchLogService logService) => _connection = client.CreateConnection<IRemoteSymbolSearchUpdateService>(logService); public void Dispose() => _connection.Dispose(); public async ValueTask<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(string source, string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithTypeResult>>( (service, cancellationToken) => service.FindPackagesWithTypeAsync(source, name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithTypeResult>.Empty; } public async ValueTask<ImmutableArray<PackageWithAssemblyResult>> FindPackagesWithAssemblyAsync( string source, string assemblyName, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<PackageWithAssemblyResult>>( (service, cancellationToken) => service.FindPackagesWithAssemblyAsync(source, assemblyName, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<PackageWithAssemblyResult>.Empty; } public async ValueTask<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync( string name, int arity, CancellationToken cancellationToken) { var result = await _connection.TryInvokeAsync<ImmutableArray<ReferenceAssemblyWithTypeResult>>( (service, cancellationToken) => service.FindReferenceAssembliesWithTypeAsync(name, arity, cancellationToken), cancellationToken).ConfigureAwait(false); return result.HasValue ? result.Value : ImmutableArray<ReferenceAssemblyWithTypeResult>.Empty; } public async ValueTask UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory, ISymbolSearchLogService logService, CancellationToken cancellationToken) { // logService parameter is ignored since it's already set on the connection as a callback _ = logService; _ = await _connection.TryInvokeAsync( (service, callbackId, cancellationToken) => service.UpdateContinuouslyAsync(callbackId, sourceName, localSettingsDirectory, cancellationToken), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/InKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class InKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInForEach1Test() VerifyRecommendationsContain(<MethodBody>For Each x |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInForEach2Test() VerifyRecommendationsContain(<MethodBody>For Each x As Goo |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x As Goo |</MethodBody>, "In") End Sub <WorkItem(543231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543231")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery3Test() VerifyRecommendationsAreExactly(<MethodBody>Dim x = From x As Integer |</MethodBody>, "In") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For Each x |</MethodBody>, "In") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For Each x _ |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For Each x _ ' Test |</MethodBody>, "In") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations Public Class InKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInForEach1Test() VerifyRecommendationsContain(<MethodBody>For Each x |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInForEach2Test() VerifyRecommendationsContain(<MethodBody>For Each x As Goo |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x As Goo |</MethodBody>, "In") End Sub <WorkItem(543231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543231")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InInFromQuery3Test() VerifyRecommendationsAreExactly(<MethodBody>Dim x = From x As Integer |</MethodBody>, "In") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <MethodBody>For Each x |</MethodBody>, "In") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody>For Each x _ |</MethodBody>, "In") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody>For Each x _ ' Test |</MethodBody>, "In") End Sub End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Compilation/DocumentationComments/DocumentationCommentCompiler.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.IO Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Private ReadOnly _assemblyName As String Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _processIncludes As Boolean Private ReadOnly _isForSingleSymbol As Boolean ' minor differences in behavior between batch case and API case. Private ReadOnly _diagnostics As BindingDiagnosticBag Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _filterSyntaxTree As SyntaxTree ' if not null, limit analysis to types residing in this tree Private ReadOnly _filterSpanWithinTree As TextSpan? ' if filterTree and filterSpanWithinTree is not null, limit analysis to types residing within this span in the filterTree. Private _writer As DocWriter 'private CommonSyntaxNodeLocationComparer lazyComparer; Private _includedFileCache As DocumentationCommentIncludeCache Private Sub New(assemblyName As String, compilation As VisualBasicCompilation, writer As TextWriter, processIncludes As Boolean, isForSingleSymbol As Boolean, diagnostics As BindingDiagnosticBag, filterTree As SyntaxTree, filterSpanWithinTree As TextSpan?, preferredCulture As CultureInfo, cancellationToken As CancellationToken) Me._assemblyName = assemblyName Me._compilation = compilation Me._writer = New DocWriter(writer) Me._processIncludes = processIncludes Me._isForSingleSymbol = isForSingleSymbol Me._diagnostics = diagnostics Me._filterSyntaxTree = filterTree Me._filterSpanWithinTree = filterSpanWithinTree Me._cancellationToken = cancellationToken End Sub ''' <summary> ''' Traverses the symbol table processing XML documentation comments and optionally writing them to a provided stream. ''' </summary> ''' <param name="compilation">Compilation that owns the symbol table.</param> ''' <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> ''' <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> ''' <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> ''' <param name="cancellationToken">To stop traversing the symbol table early.</param> ''' <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> ''' <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> Friend Shared Sub WriteDocumentationCommentXml(compilation As VisualBasicCompilation, assemblyName As String, xmlDocStream As Stream, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) Dim writer As StreamWriter = Nothing If xmlDocStream IsNot Nothing AndAlso xmlDocStream.CanWrite Then writer = New StreamWriter(xmlDocStream, New UTF8Encoding(True, False), bufferSize:=&H400, leaveOpen:=True) End If Try Using writer ' TODO: get preferred culture from compilation(?) Dim compiler As New DocumentationCommentCompiler(If(assemblyName, compilation.SourceAssembly.Name), compilation, writer, True, False, diagnostics, filterTree, filterSpanWithinTree, preferredCulture:=Nothing, cancellationToken:=cancellationToken) compiler.Visit(compilation.SourceAssembly.GlobalNamespace) Debug.Assert(compiler._writer.IndentDepth = 0) writer?.Flush() End Using Catch ex As Exception diagnostics.Add(ERRID.ERR_DocFileGen, Location.None, ex.Message) End Try If diagnostics.AccumulatesDiagnostics Then If filterTree IsNot Nothing Then MislocatedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics.DiagnosticBag, cancellationToken) Else For Each tree In compilation.SyntaxTrees MislocatedDocumentationCommentFinder.ReportUnprocessed(tree, filterSpanWithinTree:=Nothing, diagnostics.DiagnosticBag, cancellationToken) Next End If End If End Sub Private ReadOnly Property [Module] As SourceModuleSymbol Get Return DirectCast(Me._compilation.SourceModule, SourceModuleSymbol) End Get End Property ''' <summary> ''' Gets the XML that would be written to the documentation comment file for this assembly. ''' </summary> ''' <param name="symbol">The symbol for which to retrieve documentation comments.</param> ''' <param name="processIncludes">True to treat includes as semantically meaningful ''' (pull in contents from other files and bind crefs, etc).</param> ''' <param name="cancellationToken">To stop traversing the symbol table early.</param> Friend Shared Function GetDocumentationCommentXml(symbol As Symbol, processIncludes As Boolean, preferredCulture As CultureInfo, cancellationToken As CancellationToken) As String Debug.Assert(symbol.Kind = SymbolKind.Event OrElse symbol.Kind = SymbolKind.Field OrElse symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Property) Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(compilation IsNot Nothing) Dim pooled As PooledStringBuilder = PooledStringBuilder.GetInstance() Dim writer As New StringWriter(pooled.Builder, CultureInfo.InvariantCulture) Dim compiler = New DocumentationCommentCompiler(Nothing, compilation, writer, processIncludes, True, BindingDiagnosticBag.Discarded, Nothing, Nothing, preferredCulture, cancellationToken) compiler.Visit(symbol) Debug.Assert(compiler._writer.IndentDepth = 0) writer.Dispose() Return pooled.ToStringAndFree() End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.IO Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicCompilation Partial Friend Class DocumentationCommentCompiler Inherits VisualBasicSymbolVisitor Private ReadOnly _assemblyName As String Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _processIncludes As Boolean Private ReadOnly _isForSingleSymbol As Boolean ' minor differences in behavior between batch case and API case. Private ReadOnly _diagnostics As BindingDiagnosticBag Private ReadOnly _cancellationToken As CancellationToken Private ReadOnly _filterSyntaxTree As SyntaxTree ' if not null, limit analysis to types residing in this tree Private ReadOnly _filterSpanWithinTree As TextSpan? ' if filterTree and filterSpanWithinTree is not null, limit analysis to types residing within this span in the filterTree. Private _writer As DocWriter 'private CommonSyntaxNodeLocationComparer lazyComparer; Private _includedFileCache As DocumentationCommentIncludeCache Private Sub New(assemblyName As String, compilation As VisualBasicCompilation, writer As TextWriter, processIncludes As Boolean, isForSingleSymbol As Boolean, diagnostics As BindingDiagnosticBag, filterTree As SyntaxTree, filterSpanWithinTree As TextSpan?, preferredCulture As CultureInfo, cancellationToken As CancellationToken) Me._assemblyName = assemblyName Me._compilation = compilation Me._writer = New DocWriter(writer) Me._processIncludes = processIncludes Me._isForSingleSymbol = isForSingleSymbol Me._diagnostics = diagnostics Me._filterSyntaxTree = filterTree Me._filterSpanWithinTree = filterSpanWithinTree Me._cancellationToken = cancellationToken End Sub ''' <summary> ''' Traverses the symbol table processing XML documentation comments and optionally writing them to a provided stream. ''' </summary> ''' <param name="compilation">Compilation that owns the symbol table.</param> ''' <param name="assemblyName">Assembly name override, if specified. Otherwise the <see cref="ISymbol.Name"/> of the source assembly is used.</param> ''' <param name="xmlDocStream">Stream to which XML will be written, if specified.</param> ''' <param name="diagnostics">Will be supplemented with documentation comment diagnostics.</param> ''' <param name="cancellationToken">To stop traversing the symbol table early.</param> ''' <param name="filterTree">Only report diagnostics from this syntax tree, if non-null.</param> ''' <param name="filterSpanWithinTree">If <paramref name="filterTree"/> and filterSpanWithinTree is non-null, report diagnostics within this span in the <paramref name="filterTree"/>.</param> Friend Shared Sub WriteDocumentationCommentXml(compilation As VisualBasicCompilation, assemblyName As String, xmlDocStream As Stream, diagnostics As BindingDiagnosticBag, cancellationToken As CancellationToken, Optional filterTree As SyntaxTree = Nothing, Optional filterSpanWithinTree As TextSpan? = Nothing) Dim writer As StreamWriter = Nothing If xmlDocStream IsNot Nothing AndAlso xmlDocStream.CanWrite Then writer = New StreamWriter(xmlDocStream, New UTF8Encoding(True, False), bufferSize:=&H400, leaveOpen:=True) End If Try Using writer ' TODO: get preferred culture from compilation(?) Dim compiler As New DocumentationCommentCompiler(If(assemblyName, compilation.SourceAssembly.Name), compilation, writer, True, False, diagnostics, filterTree, filterSpanWithinTree, preferredCulture:=Nothing, cancellationToken:=cancellationToken) compiler.Visit(compilation.SourceAssembly.GlobalNamespace) Debug.Assert(compiler._writer.IndentDepth = 0) writer?.Flush() End Using Catch ex As Exception diagnostics.Add(ERRID.ERR_DocFileGen, Location.None, ex.Message) End Try If diagnostics.AccumulatesDiagnostics Then If filterTree IsNot Nothing Then MislocatedDocumentationCommentFinder.ReportUnprocessed(filterTree, filterSpanWithinTree, diagnostics.DiagnosticBag, cancellationToken) Else For Each tree In compilation.SyntaxTrees MislocatedDocumentationCommentFinder.ReportUnprocessed(tree, filterSpanWithinTree:=Nothing, diagnostics.DiagnosticBag, cancellationToken) Next End If End If End Sub Private ReadOnly Property [Module] As SourceModuleSymbol Get Return DirectCast(Me._compilation.SourceModule, SourceModuleSymbol) End Get End Property ''' <summary> ''' Gets the XML that would be written to the documentation comment file for this assembly. ''' </summary> ''' <param name="symbol">The symbol for which to retrieve documentation comments.</param> ''' <param name="processIncludes">True to treat includes as semantically meaningful ''' (pull in contents from other files and bind crefs, etc).</param> ''' <param name="cancellationToken">To stop traversing the symbol table early.</param> Friend Shared Function GetDocumentationCommentXml(symbol As Symbol, processIncludes As Boolean, preferredCulture As CultureInfo, cancellationToken As CancellationToken) As String Debug.Assert(symbol.Kind = SymbolKind.Event OrElse symbol.Kind = SymbolKind.Field OrElse symbol.Kind = SymbolKind.Method OrElse symbol.Kind = SymbolKind.NamedType OrElse symbol.Kind = SymbolKind.Property) Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(compilation IsNot Nothing) Dim pooled As PooledStringBuilder = PooledStringBuilder.GetInstance() Dim writer As New StringWriter(pooled.Builder, CultureInfo.InvariantCulture) Dim compiler = New DocumentationCommentCompiler(Nothing, compilation, writer, processIncludes, True, BindingDiagnosticBag.Discarded, Nothing, Nothing, preferredCulture, cancellationToken) compiler.Visit(symbol) Debug.Assert(compiler._writer.IndentDepth = 0) writer.Dispose() Return pooled.ToStringAndFree() End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source4.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:module /out:Source4Module.netmodule /vbruntime- Source4.vb ' vbc /t:library /out:c4.dll /vbruntime- Source4.vb Public Class C4 End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. ' vbc /t:module /out:Source4Module.netmodule /vbruntime- Source4.vb ' vbc /t:library /out:c4.dll /vbruntime- Source4.vb Public Class C4 End Class
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Storage/StorageOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Storage { internal static class StorageOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; public const string OptionName = "FeatureManager/Storage"; public static readonly Option<StorageDatabase> Database = new( OptionName, nameof(Database), defaultValue: StorageDatabase.SQLite, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Database))); /// <summary> /// Option that can be set in certain scenarios (like tests) to indicate that the client expects the DB to /// succeed at all work and that it should not ever gracefully fall over. Should not be set in normal host /// environments, where it is completely reasonable for things to fail (for example, if a client asks for a key /// that hasn't been stored yet). /// </summary> public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false); } [ExportOptionProvider, Shared] internal class RemoteHostOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteHostOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( StorageOptions.Database, StorageOptions.DatabaseMustSucceed); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.Storage { internal static class StorageOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; public const string OptionName = "FeatureManager/Storage"; public static readonly Option<StorageDatabase> Database = new( OptionName, nameof(Database), defaultValue: StorageDatabase.SQLite, storageLocations: new LocalUserProfileStorageLocation(LocalRegistryPath + nameof(Database))); /// <summary> /// Option that can be set in certain scenarios (like tests) to indicate that the client expects the DB to /// succeed at all work and that it should not ever gracefully fall over. Should not be set in normal host /// environments, where it is completely reasonable for things to fail (for example, if a client asks for a key /// that hasn't been stored yet). /// </summary> public static readonly Option<bool> DatabaseMustSucceed = new(OptionName, nameof(DatabaseMustSucceed), defaultValue: false); } [ExportOptionProvider, Shared] internal class RemoteHostOptionsProvider : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteHostOptionsProvider() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( StorageOptions.Database, StorageOptions.DatabaseMustSucceed); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeAccessorFunction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind) { var newElement = new CodeAccessorFunction(state, parent, kind); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly MethodKind _kind; private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind) : base(state, parent.FileCodeModel) { Debug.Assert(kind == MethodKind.EventAdd || kind == MethodKind.EventRaise || kind == MethodKind.EventRemove || kind == MethodKind.PropertyGet || kind == MethodKind.PropertySet); _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _kind = kind; } private AbstractCodeMember ParentMember => _parentHandle.Value; private bool IsPropertyAccessor() => _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet; internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } return CodeModelService.TryGetAutoPropertyExpressionBody(parentNode, out node) || CodeModelService.TryGetAccessorNode(parentNode, _kind, out node); } public override EnvDTE.vsCMElement Kind => EnvDTE.vsCMElement.vsCMElementFunction; public override object Parent => _parentHandle.Value; public override EnvDTE.CodeElements Children => EmptyCollection.Create(this.State, this); protected override string GetName() => this.ParentMember.Name; protected override void SetName(string value) => this.ParentMember.Name = value; protected override string GetFullName() => this.ParentMember.FullName; public EnvDTE.CodeElements Attributes => AttributeCollection.Create(this.State, this); public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public bool CanOverride { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public string Comment { get { throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.vsCMFunction FunctionKind { get { if (!(LookupSymbol() is IMethodSymbol methodSymbol)) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(methodSymbol); } } public bool IsGeneric { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsGeneric; } else { return ((CodeEvent)this.ParentMember).IsGeneric; } } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).OverrideKind; } else { return ((CodeEvent)this.ParentMember).OverrideKind; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).OverrideKind = value; } else { ((CodeEvent)this.ParentMember).OverrideKind = value; } } } public bool IsOverloaded => false; public bool IsShared { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsShared; } else { return ((CodeEvent)this.ParentMember).IsShared; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).IsShared = value; } else { ((CodeEvent)this.ParentMember).IsShared = value; } } } public bool MustImplement { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).MustImplement; } else { return ((CodeEvent)this.ParentMember).MustImplement; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).MustImplement = value; } else { ((CodeEvent)this.ParentMember).MustImplement = value; } } } public EnvDTE.CodeElements Overloads => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElements Parameters { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Parameters; } throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Type; } throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public void RemoveParameter(object element) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind) { var newElement = new CodeAccessorFunction(state, parent, kind); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly MethodKind _kind; private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind) : base(state, parent.FileCodeModel) { Debug.Assert(kind == MethodKind.EventAdd || kind == MethodKind.EventRaise || kind == MethodKind.EventRemove || kind == MethodKind.PropertyGet || kind == MethodKind.PropertySet); _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _kind = kind; } private AbstractCodeMember ParentMember => _parentHandle.Value; private bool IsPropertyAccessor() => _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet; internal override bool TryLookupNode(out SyntaxNode node) { node = null; var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { return false; } return CodeModelService.TryGetAutoPropertyExpressionBody(parentNode, out node) || CodeModelService.TryGetAccessorNode(parentNode, _kind, out node); } public override EnvDTE.vsCMElement Kind => EnvDTE.vsCMElement.vsCMElementFunction; public override object Parent => _parentHandle.Value; public override EnvDTE.CodeElements Children => EmptyCollection.Create(this.State, this); protected override string GetName() => this.ParentMember.Name; protected override void SetName(string value) => this.ParentMember.Name = value; protected override string GetFullName() => this.ParentMember.FullName; public EnvDTE.CodeElements Attributes => AttributeCollection.Create(this.State, this); public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public bool CanOverride { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public string Comment { get { throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.vsCMFunction FunctionKind { get { if (!(LookupSymbol() is IMethodSymbol methodSymbol)) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(methodSymbol); } } public bool IsGeneric { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsGeneric; } else { return ((CodeEvent)this.ParentMember).IsGeneric; } } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).OverrideKind; } else { return ((CodeEvent)this.ParentMember).OverrideKind; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).OverrideKind = value; } else { ((CodeEvent)this.ParentMember).OverrideKind = value; } } } public bool IsOverloaded => false; public bool IsShared { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsShared; } else { return ((CodeEvent)this.ParentMember).IsShared; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).IsShared = value; } else { ((CodeEvent)this.ParentMember).IsShared = value; } } } public bool MustImplement { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).MustImplement; } else { return ((CodeEvent)this.ParentMember).MustImplement; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).MustImplement = value; } else { ((CodeEvent)this.ParentMember).MustImplement = value; } } } public EnvDTE.CodeElements Overloads => throw Exceptions.ThrowEFail(); public EnvDTE.CodeElements Parameters { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Parameters; } throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Type; } throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public void RemoveParameter(object element) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Remote/ServiceHub/Services/ProjectTelemetry/ApiUsageIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => 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; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.Remote.Telemetry { /// <summary> /// Creates an <see cref="IIncrementalAnalyzer"/> that collects Api usage information from metadata references /// in current solution. /// </summary> [ExportIncrementalAnalyzerProvider(nameof(ApiUsageIncrementalAnalyzerProvider), new[] { WorkspaceKind.RemoteWorkspace }), Shared] internal sealed class ApiUsageIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ApiUsageIncrementalAnalyzerProvider() { } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { #if DEBUG return new Analyzer(workspace.Services); #else return null; #endif } private sealed class Analyzer : IIncrementalAnalyzer { private readonly HostWorkspaceServices _services; // maximum number of symbols to report per project. private const int Max = 2000; private readonly HashSet<ProjectId> _reported = new HashSet<ProjectId>(); public Analyzer(HostWorkspaceServices services) { _services = services; } public Task RemoveProjectAsync(ProjectId projectId, CancellationToken cancellationToken) { lock (_reported) { _reported.Remove(projectId); } return Task.CompletedTask; } public async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { var telemetryService = _services.GetRequiredService<IWorkspaceTelemetryService>(); if (!telemetryService.HasActiveSession) { return; } lock (_reported) { // to make sure that we don't report while solution load, we do this heuristic. // if the reason we are called is due to "document being added" to project, we wait for next analyze call. // also, we only report usage information per project once. // this telemetry will only let us know which API ever used, this doesn't care how often/many times an API // used. and this data is approximation not precise information. and we don't care much on how many times // APIs used in the same solution. we are rather more interested in number of solutions or users APIs are used. if (reasons.Contains(PredefinedInvocationReasons.DocumentAdded) || !_reported.Add(project.Id)) { return; } } // if this project has cross language p2p references, then pass in solution, otherwise, don't give in // solution since checking whether symbol is cross language symbol or not is expansive and // we know that population of solution with both C# and VB are very tiny. // so no reason to pay the cost for common cases. var crossLanguageSolutionOpt = project.ProjectReferences.Any(p => project.Solution.GetProject(p.ProjectId)?.Language != project.Language) ? project.Solution : null; var metadataSymbolUsed = new HashSet<ISymbol>(SymbolEqualityComparer.Default); foreach (var document in project.Documents) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var operation in GetOperations(model, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (metadataSymbolUsed.Count > Max) { // collect data up to max per project break; } // this only gather reference and method call symbols but not type being used. // if we want all types from metadata used, we need to add more cases // which will make things more expansive. CollectApisUsed(operation, crossLanguageSolutionOpt, metadataSymbolUsed, cancellationToken); } } var solutionSessionId = project.Solution.State.SolutionAttributes.TelemetryId; var projectGuid = project.State.ProjectInfo.Attributes.TelemetryId; telemetryService.ReportApiUsage(metadataSymbolUsed, solutionSessionId, projectGuid); return; // local functions static void CollectApisUsed( IOperation operation, Solution solutionOpt, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { switch (operation) { case IMemberReferenceOperation memberOperation: AddIfMetadataSymbol(solutionOpt, memberOperation.Member, metadataSymbolUsed, cancellationToken); break; case IInvocationOperation invocationOperation: AddIfMetadataSymbol(solutionOpt, invocationOperation.TargetMethod, metadataSymbolUsed, cancellationToken); break; case IObjectCreationOperation objectCreation: AddIfMetadataSymbol(solutionOpt, objectCreation.Constructor, metadataSymbolUsed, cancellationToken); break; } } static void AddIfMetadataSymbol( Solution solutionOpt, ISymbol symbol, HashSet<ISymbol> metadataSymbolUsed, CancellationToken cancellationToken) { // get symbol as it is defined in metadata symbol = symbol.OriginalDefinition; if (metadataSymbolUsed.Contains(symbol)) { return; } if (symbol.Locations.All(l => l.Kind == LocationKind.MetadataFile) && solutionOpt?.GetProject(symbol.ContainingAssembly, cancellationToken) == null) { metadataSymbolUsed.Add(symbol); } } static IEnumerable<IOperation> GetOperations(SemanticModel model, CancellationToken cancellationToken) { // root is already there var root = model.SyntaxTree.GetRoot(cancellationToken); // go through all nodes until we find first node that has IOperation foreach (var rootOperation in root.DescendantNodes(n => model.GetOperation(n, cancellationToken) == null) .Select(n => model.GetOperation(n, cancellationToken)) .Where(o => o != null)) { foreach (var operation in rootOperation.DescendantsAndSelf()) { yield return operation; } } } } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) => Task.CompletedTask; public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) => Task.CompletedTask; public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) => false; public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) => Task.CompletedTask; public Task RemoveDocumentAsync(DocumentId documentId, CancellationToken cancellationToken) => Task.CompletedTask; } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/AbstractVisualBasicCompletionProviderTests.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.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Imports RoslynCompletion = Microsoft.CodeAnalysis.Completion Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public MustInherit Class AbstractVisualBasicCompletionProviderTests Inherits AbstractCompletionProviderTests(Of VisualBasicTestWorkspaceFixture) Protected Overrides Function CreateWorkspace(fileContents As String) As TestWorkspace Return TestWorkspace.CreateVisualBasic(fileContents, exportProvider:=ExportProvider) End Function Friend Overrides Function GetCompletionService(project As Project) As CompletionServiceWithProviders Return Assert.IsType(Of VisualBasicCompletionService)(MyBase.GetCompletionService(project)) End Function Private Protected Overrides Function BaseVerifyWorkerAsync( code As String, position As Integer, expectedItemOrNull As String, expectedDescriptionOrNull As String, sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean, checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?, hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String, isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task Return MyBase.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) End Function Private Protected Overrides Async Function VerifyWorkerAsync( code As String, position As Integer, expectedItemOrNull As String, expectedDescriptionOrNull As String, sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean, checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?, hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String, isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task ' Script/interactive support removed for now. ' TODO: Re-enable these when interactive is back in the product. If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then Return End If Await VerifyAtPositionAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) Await VerifyAtEndOfFileAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) ' Items cannot be partially written if we're checking for their absence, ' or if we're verifying that the list will show up (without specifying an actual item) If Not checkForAbsence AndAlso expectedItemOrNull <> Nothing Then Await VerifyAtPosition_ItemPartiallyWrittenAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters) Await VerifyAtEndOfFile_ItemPartiallyWrittenAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters) End If End Function Protected Overrides Async Function VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit As String, position As Integer, itemToCommit As String, expectedCodeAfterCommit As String, sourceCodeKind As SourceCodeKind, Optional commitChar As Char? = Nothing) As Task ' Script/interactive support removed for now. ' TODO: Re-enable these when interactive is back in the product. If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then Return End If Await MyBase.VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind, commitChar) End Function Protected Overrides Function ItemPartiallyWritten(expectedItemOrNull As String) As String If expectedItemOrNull(0) = "[" Then Return expectedItemOrNull.Substring(1, 1) End If Return expectedItemOrNull.Substring(0, 1) End Function Protected Shared Function AddInsideMethod(text As String) As String Return "Class C" & vbCrLf & " Function F()" & vbCrLf & " " & text & vbCrLf & " End Function" & vbCrLf & "End Class" End Function Protected Shared Function CreateContent(ParamArray contents As String()) As String Return String.Join(vbCrLf, contents) End Function Protected Shared Function AddImportsStatement(importsStatement As String, text As String) As String Return importsStatement & vbCrLf & vbCrLf & text End Function Protected Async Function VerifySendEnterThroughToEditorAsync( initialMarkup As String, textTypedSoFar As String, expected As Boolean, Optional sourceCodeKind As SourceCodeKind = SourceCodeKind.Regular) As Task Using workspace = TestWorkspace.CreateVisualBasic(initialMarkup, exportProvider:=ExportProvider) Dim hostDocument = workspace.DocumentWithCursor workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind) Dim documentId = workspace.GetDocumentId(hostDocument) Dim document = workspace.CurrentSolution.GetDocument(documentId) Dim position = hostDocument.CursorPosition.Value Dim service = GetCompletionService(document.Project) Dim completionList = Await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke) Dim item = completionList.Items.First(Function(i) i.DisplayText.StartsWith(textTypedSoFar)) Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)) End Using End Function Protected Sub TestCommonIsTextualTriggerCharacter() Dim alwaysTriggerList = { "goo$$.", "goo$$[", "goo$$#", "goo$$ ", "goo$$=" } For Each markup In alwaysTriggerList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=True) Next Dim triggerOnlyWithLettersList = { "$$a", "$$_" } For Each markup In triggerOnlyWithLettersList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=False) Next Dim neverTriggerList = { "goo$$x", "goo$$_" } For Each markup In neverTriggerList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=False, shouldTriggerWithTriggerOnLettersDisabled:=False) Next 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.Completion Imports Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Completion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.Completion Imports Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data Imports RoslynCompletion = Microsoft.CodeAnalysis.Completion Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders Public MustInherit Class AbstractVisualBasicCompletionProviderTests Inherits AbstractCompletionProviderTests(Of VisualBasicTestWorkspaceFixture) Protected Overrides Function CreateWorkspace(fileContents As String) As TestWorkspace Return TestWorkspace.CreateVisualBasic(fileContents, exportProvider:=ExportProvider) End Function Friend Overrides Function GetCompletionService(project As Project) As CompletionServiceWithProviders Return Assert.IsType(Of VisualBasicCompletionService)(MyBase.GetCompletionService(project)) End Function Private Protected Overrides Function BaseVerifyWorkerAsync( code As String, position As Integer, expectedItemOrNull As String, expectedDescriptionOrNull As String, sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean, checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?, hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String, isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task Return MyBase.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) End Function Private Protected Overrides Async Function VerifyWorkerAsync( code As String, position As Integer, expectedItemOrNull As String, expectedDescriptionOrNull As String, sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean, checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?, hasSuggestionItem As Boolean?, displayTextSuffix As String, displayTextPrefix As String, inlineDescription As String, isComplexTextEdit As Boolean?, matchingFilters As List(Of CompletionFilter), flags As CompletionItemFlags?) As Task ' Script/interactive support removed for now. ' TODO: Re-enable these when interactive is back in the product. If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then Return End If Await VerifyAtPositionAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) Await VerifyAtEndOfFileAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags) ' Items cannot be partially written if we're checking for their absence, ' or if we're verifying that the list will show up (without specifying an actual item) If Not checkForAbsence AndAlso expectedItemOrNull <> Nothing Then Await VerifyAtPosition_ItemPartiallyWrittenAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters) Await VerifyAtEndOfFile_ItemPartiallyWrittenAsync( code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters) End If End Function Protected Overrides Async Function VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit As String, position As Integer, itemToCommit As String, expectedCodeAfterCommit As String, sourceCodeKind As SourceCodeKind, Optional commitChar As Char? = Nothing) As Task ' Script/interactive support removed for now. ' TODO: Re-enable these when interactive is back in the product. If sourceCodeKind <> Microsoft.CodeAnalysis.SourceCodeKind.Regular Then Return End If Await MyBase.VerifyCustomCommitProviderWorkerAsync(codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind, commitChar) End Function Protected Overrides Function ItemPartiallyWritten(expectedItemOrNull As String) As String If expectedItemOrNull(0) = "[" Then Return expectedItemOrNull.Substring(1, 1) End If Return expectedItemOrNull.Substring(0, 1) End Function Protected Shared Function AddInsideMethod(text As String) As String Return "Class C" & vbCrLf & " Function F()" & vbCrLf & " " & text & vbCrLf & " End Function" & vbCrLf & "End Class" End Function Protected Shared Function CreateContent(ParamArray contents As String()) As String Return String.Join(vbCrLf, contents) End Function Protected Shared Function AddImportsStatement(importsStatement As String, text As String) As String Return importsStatement & vbCrLf & vbCrLf & text End Function Protected Async Function VerifySendEnterThroughToEditorAsync( initialMarkup As String, textTypedSoFar As String, expected As Boolean, Optional sourceCodeKind As SourceCodeKind = SourceCodeKind.Regular) As Task Using workspace = TestWorkspace.CreateVisualBasic(initialMarkup, exportProvider:=ExportProvider) Dim hostDocument = workspace.DocumentWithCursor workspace.OnDocumentSourceCodeKindChanged(hostDocument.Id, sourceCodeKind) Dim documentId = workspace.GetDocumentId(hostDocument) Dim document = workspace.CurrentSolution.GetDocument(documentId) Dim position = hostDocument.CursorPosition.Value Dim service = GetCompletionService(document.Project) Dim completionList = Await GetCompletionListAsync(service, document, position, RoslynCompletion.CompletionTrigger.Invoke) Dim item = completionList.Items.First(Function(i) i.DisplayText.StartsWith(textTypedSoFar)) Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)) End Using End Function Protected Sub TestCommonIsTextualTriggerCharacter() Dim alwaysTriggerList = { "goo$$.", "goo$$[", "goo$$#", "goo$$ ", "goo$$=" } For Each markup In alwaysTriggerList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=True) Next Dim triggerOnlyWithLettersList = { "$$a", "$$_" } For Each markup In triggerOnlyWithLettersList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=True, shouldTriggerWithTriggerOnLettersDisabled:=False) Next Dim neverTriggerList = { "goo$$x", "goo$$_" } For Each markup In neverTriggerList VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled:=False, shouldTriggerWithTriggerOnLettersDisabled:=False) Next End Sub End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/Completion/ArgumentProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Completion { internal abstract class ArgumentProvider { public string Name { get; } protected ArgumentProvider() => Name = GetType().FullName!; /// <summary> /// Supports providing argument values for an argument completion session. /// </summary> /// <remarks> /// See <see cref="ArgumentContext"/> for more information about argument values. /// </remarks> /// <param name="context">The argument context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public abstract Task ProvideArgumentAsync(ArgumentContext context); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Completion { internal abstract class ArgumentProvider { public string Name { get; } protected ArgumentProvider() => Name = GetType().FullName!; /// <summary> /// Supports providing argument values for an argument completion session. /// </summary> /// <remarks> /// See <see cref="ArgumentContext"/> for more information about argument values. /// </remarks> /// <param name="context">The argument context.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public abstract Task ProvideArgumentAsync(ArgumentContext context); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Syntax/Parsing/DeclarationParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DeclarationParsingTests : ParsingTests { public DeclarationParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular); } [Fact] public void TestExternAlias() { var text = "extern alias a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Externs.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ea = file.Externs[0]; Assert.NotEqual(default, ea.ExternKeyword); Assert.Equal(SyntaxKind.ExternKeyword, ea.ExternKeyword.Kind()); Assert.NotEqual(default, ea.AliasKeyword); Assert.Equal(SyntaxKind.AliasKeyword, ea.AliasKeyword.Kind()); Assert.False(ea.AliasKeyword.IsMissing); Assert.NotEqual(default, ea.Identifier); Assert.Equal("a", ea.Identifier.ToString()); Assert.NotEqual(default, ea.SemicolonToken); } [Fact] public void TestUsing() { var text = "using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Null(ud.Alias); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStatic() { var text = "using static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticInWrongOrder() { var text = "static using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToFullString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_NamespaceUnexpected, errors[0].Code); } [Fact] public void TestDuplicateStatic() { var text = "using static static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingNamespace() { var text = "using namespace a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingDottedName() { var text = "using a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticDottedName() { var text = "using static a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticGenericName() { var text = "using static a<int?>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a<int?>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasName() { var text = "using a = b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasGenericName() { var text = "using a = b<c>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b<c>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestGlobalAttribute() { var text = "[assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Verbatim() { var text = "[@assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@assembly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Escape() { var text = @"[as\u0073embly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal(@"as\u0073embly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute() { var text = "[module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.ModuleKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute_Verbatim() { var text = "[@module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Module, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithParentheses() { var text = "[assembly:a()]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.AssemblyKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(0, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleArguments() { var text = "[assembly:a(b, c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(2, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[1].ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithNamedArguments() { var text = "[assembly:a(b = c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(1, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b = c", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.EqualsToken); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].Expression); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[0].Expression.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleAttributes() { var text = "[assembly:a, b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(2, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotNull(ad.Attributes[1].Name); Assert.Equal("b", ad.Attributes[1].Name.ToString()); Assert.Null(ad.Attributes[1].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestMultipleGlobalAttributeDeclarations() { var text = "[assembly:a] [assembly:b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(2, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); ad = (AttributeListSyntax)file.AttributeLists[1]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("b", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestNamespace() { var text = "namespace a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespace() { var text = "namespace a;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithDottedName() { var text = "namespace a.b.c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a.b.c", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithUsing() { var text = "namespace a { using b.c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b.c;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespaceWithUsing() { var text = "namespace a; using b.c;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b.c;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithExternAlias() { var text = "namespace a { extern alias b; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Externs.Count); Assert.Equal("extern alias b;", ns.Externs[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespaceWithExternAlias() { var text = "namespace a; extern alias b;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(1, ns.Externs.Count); Assert.Equal("extern alias b;", ns.Externs[0].ToString()); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithExternAliasFollowingUsingBad() { var text = "namespace a { using b; extern alias c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Externs.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithNestedNamespace() { var text = "namespace a { namespace b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(1, ns.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, ns.Members[0].Kind()); var ns2 = (NamespaceDeclarationSyntax)ns.Members[0]; Assert.NotEqual(default, ns2.NamespaceKeyword); Assert.NotNull(ns2.Name); Assert.Equal("b", ns2.Name.ToString()); Assert.NotEqual(default, ns2.OpenBraceToken); Assert.Equal(0, ns2.Usings.Count); Assert.Equal(0, ns2.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestClass() { var text = "class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPublic() { var text = "public class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithInternal() { var text = "internal class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStatic() { var text = "static class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithSealed() { var text = "sealed class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.SealedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAbstract() { var text = "abstract class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.AbstractKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPartial() { var text = "partial class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAttribute() { var text = "[attr] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributes() { var text = "[attr1] [attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, cs.AttributeLists.Count); Assert.Equal("[attr1]", cs.AttributeLists[0].ToString()); Assert.Equal("[attr2]", cs.AttributeLists[1].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributesInAList() { var text = "[attr1, attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr1, attr2]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithBaseType() { var text = "class a : b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(1, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleBases() { var text = "class a : b, c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("c", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithTypeConstraintBound() { var text = "class a<b> where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNonGenericClassWithTypeConstraintBound() { var text = "class a where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,9): error CS0080: Constraints are not allowed on non-generic declarations // class a where b : c { } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 9)); } [Fact] public void TestNonGenericMethodWithTypeConstraintBound() { var text = "class a { void M() where b : c { } }"; CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,20): error CS0080: Constraints are not allowed on non-generic declarations // class a { void M() where b : c { } } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 20)); } [Fact] public void TestClassWithNewConstraintBound() { var text = "class a<b> where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithClassConstraintBound() { var text = "class a<b> where b : class { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStructConstraintBound() { var text = "class a<b> where b : struct { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.StructConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.StructKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraintBounds() { var text = "class a<b> where b : class, c, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints() { var text = "class a<b> where b : c where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.False(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints001() { var text = "class a<b> where b : c where b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(2, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleConstraints002() { var text = "class a<b> where b : c where { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.True(cs.ConstraintClauses[1].Name.IsMissing); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleBasesAndConstraints() { var text = "class a<b> : c, d where b : class, e, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("c", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("d", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("e", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestInterface() { var text = "interface a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterface() { var text = "interface A<B> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<B>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(0, gn.Parameters[0].AttributeLists.Count); Assert.Equal(SyntaxKind.None, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Equal("B", gn.Parameters[0].Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterfaceWithAttributesAndVariance() { var text = "interface A<[B] out C> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<[B] out C>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(1, gn.Parameters[0].AttributeLists.Count); Assert.Equal("B", gn.Parameters[0].AttributeLists[0].Attributes[0].Name.ToString()); Assert.NotEqual(default, gn.Parameters[0].VarianceKeyword); Assert.Equal(SyntaxKind.OutKeyword, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestStruct() { var text = "struct a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.StructKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedClass() { var text = "class a { class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPrivateClass() { var text = "class a { private class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PrivateKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedClass() { var text = "class a { protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedInternalClass() { var text = "class a { protected internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalProtectedClass() { var text = "class a { internal protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPublicClass() { var text = "class a { public class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalClass() { var text = "class a { internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestDelegate() { var text = "delegate a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefReturnType() { var text = "delegate ref a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestDelegateWithRefReadonlyReturnType() { var text = "delegate ref readonly a b();"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref readonly a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInReturnTypes() { TestDelegateWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInReturnType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate " + typeText + " b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal(typeText, ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInParameterTypes() { TestDelegateWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInParameterType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate a b(" + typeText + " c);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameter() { var text = "delegate a b(c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithMultipleParameters() { var text = "delegate a b(c d, e f);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ds.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[1].Type); Assert.Equal("e", ds.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ds.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefParameter() { var text = "delegate a b(ref c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.RefKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithOutParameter() { var text = "delegate a b(out c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.OutKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParamsParameter() { var text = "delegate a b(params c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.ParamsKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithArgListParameter() { var text = "delegate a b(__arglist);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ds.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameterAttribute() { var text = "delegate a b([attr] c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal("[attr]", ds.ParameterList.Parameters[0].AttributeLists[0].ToString()); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestNestedDelegate() { var text = "class a { delegate b c(); }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, cs.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("b", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("c", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestClassMethod() { var text = "class a { b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRefReturn() { var text = "class a { ref b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonlyReturn() { var text = "class a { ref readonly b X() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref readonly b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRef() { var text = "class a { ref }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonly() { var text = "class a { ref readonly }"; var file = this.ParseFile(text, parseOptions: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } private void TestClassMethodModifiers(params SyntaxKind[] modifiers) { var text = "class a { " + string.Join(" ", modifiers.Select(SyntaxFacts.GetText)) + " b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(modifiers.Length, ms.Modifiers.Count); for (int i = 0; i < modifiers.Length; ++i) { Assert.Equal(modifiers[i], ms.Modifiers[i].Kind()); } Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodAccessModes() { TestClassMethodModifiers(SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.PrivateKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword); TestClassMethodModifiers(SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodModifiersOrder() { TestClassMethodModifiers(SyntaxKind.PublicKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodWithPartial() { var text = "class a { partial void M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructMethodWithReadonly() { var text = "struct a { readonly void M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestReadOnlyRefReturning() { var text = "struct a { readonly ref readonly int M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.RefType, ms.ReturnType.Kind()); var rt = (RefTypeSyntax)ms.ReturnType; Assert.Equal(SyntaxKind.RefKeyword, rt.RefKeyword.Kind()); Assert.Equal(SyntaxKind.ReadOnlyKeyword, rt.ReadOnlyKeyword.Kind()); Assert.Equal("int", rt.Type.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructExpressionPropertyWithReadonly() { var text = "struct a { readonly int M => 42; }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(1, propertySyntax.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, propertySyntax.Modifiers[0].Kind()); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("M", propertySyntax.Identifier.ToString()); Assert.NotNull(propertySyntax.ExpressionBody); Assert.NotEqual(SyntaxKind.None, propertySyntax.ExpressionBody.ArrowToken.Kind()); Assert.NotNull(propertySyntax.ExpressionBody.Expression); Assert.Equal(SyntaxKind.SemicolonToken, propertySyntax.SemicolonToken.Kind()); } [Fact] public void TestStructGetterPropertyWithReadonly() { var text = "struct a { int P { readonly get { return 42; } } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(0, propertySyntax.Modifiers.Count); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("P", propertySyntax.Identifier.ToString()); var accessors = propertySyntax.AccessorList.Accessors; Assert.Equal(1, accessors.Count); Assert.Equal(1, accessors[0].Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, accessors[0].Modifiers[0].Kind()); } [Fact] public void TestStructBadExpressionProperty() { var text = @"public struct S { public int P readonly => 0; } "; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemicolonExpected, (ErrorCode)file.Errors()[0].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[1].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[2].Code); } [Fact] public void TestClassMethodWithParameter() { var text = "class a { b X(c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithMultipleParameters() { var text = "class a { b X(c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ms.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[1].Type); Assert.Equal("e", ms.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ms.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } private void TestClassMethodWithParameterModifier(SyntaxKind mod) { var text = "class a { b X(" + SyntaxFacts.GetText(mod) + " c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(mod, ms.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithParameterModifiers() { TestClassMethodWithParameterModifier(SyntaxKind.RefKeyword); TestClassMethodWithParameterModifier(SyntaxKind.OutKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ParamsKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ThisKeyword); } [Fact] public void TestClassMethodWithArgListParameter() { var text = "class a { b X(__arglist) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ms.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal(SyntaxKind.ArgListKeyword, ms.ParameterList.Parameters[0].Identifier.Kind()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInReturnTypes() { TestClassMethodWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInReturnType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal(typeText, ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInParameterTypes() { TestClassMethodWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInParameterType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { b X(" + typeText + " c) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethod() { var text = "class a { b<c> M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b<c>", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethodWithTypeConstraintBound() { var text = "class a { b X<c>() where b : d { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.NotNull(ms.TypeParameterList); Assert.Equal("X", ms.Identifier.ToString()); Assert.Equal("<c>", ms.TypeParameterList.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses.Count); Assert.NotEqual(default, ms.ConstraintClauses[0].WhereKeyword); Assert.NotNull(ms.ConstraintClauses[0].Name); Assert.Equal("b", ms.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, ms.ConstraintClauses[0].ColonToken); Assert.False(ms.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, ms.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)ms.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("d", typeBound.Type.ToString()); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [WorkItem(899685, "DevDiv/Personal")] [Fact] public void TestGenericClassConstructor() { var text = @" class Class1<T>{ public Class1() { } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); // verify that we can roundtrip Assert.Equal(text, file.ToFullString()); // verify that we don't produce any errors Assert.Equal(0, file.Errors().Length); } [Fact] public void TestClassConstructor() { var text = "class a { a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } private void TestClassConstructorWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(1, cn.Modifiers.Count); Assert.Equal(mod, cn.Modifiers[0].Kind()); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassConstructorWithModifiers() { TestClassConstructorWithModifier(SyntaxKind.PublicKeyword); TestClassConstructorWithModifier(SyntaxKind.PrivateKeyword); TestClassConstructorWithModifier(SyntaxKind.ProtectedKeyword); TestClassConstructorWithModifier(SyntaxKind.InternalKeyword); TestClassConstructorWithModifier(SyntaxKind.StaticKeyword); } [Fact] public void TestClassDestructor() { var text = "class a { ~a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DestructorDeclaration, cs.Members[0].Kind()); var cn = (DestructorDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, cn.TildeToken); Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassField() { var text = "class a { b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithBuiltInTypes() { TestClassFieldWithBuiltInType(SyntaxKind.BoolKeyword); TestClassFieldWithBuiltInType(SyntaxKind.SByteKeyword); TestClassFieldWithBuiltInType(SyntaxKind.IntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UIntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.LongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ULongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.FloatKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassFieldWithBuiltInType(SyntaxKind.StringKeyword); TestClassFieldWithBuiltInType(SyntaxKind.CharKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassFieldWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal(typeText, fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } private void TestClassFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldModifiers() { TestClassFieldModifier(SyntaxKind.PublicKeyword); TestClassFieldModifier(SyntaxKind.PrivateKeyword); TestClassFieldModifier(SyntaxKind.ProtectedKeyword); TestClassFieldModifier(SyntaxKind.InternalKeyword); TestClassFieldModifier(SyntaxKind.StaticKeyword); TestClassFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassFieldModifier(SyntaxKind.VolatileKeyword); TestClassFieldModifier(SyntaxKind.ExternKeyword); } private void TestClassEventFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventFieldDeclaration, cs.Members[0].Kind()); var fs = (EventFieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotEqual(default, fs.EventKeyword); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassEventFieldModifiers() { TestClassEventFieldModifier(SyntaxKind.PublicKeyword); TestClassEventFieldModifier(SyntaxKind.PrivateKeyword); TestClassEventFieldModifier(SyntaxKind.ProtectedKeyword); TestClassEventFieldModifier(SyntaxKind.InternalKeyword); TestClassEventFieldModifier(SyntaxKind.StaticKeyword); TestClassEventFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassEventFieldModifier(SyntaxKind.VolatileKeyword); TestClassEventFieldModifier(SyntaxKind.ExternKeyword); } [Fact] public void TestClassConstField() { var text = "class a { const b c = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.ConstKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("d", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithInitializer() { var text = "class a { b c = e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("e", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithArrayInitializer() { var text = "class a { b c = { }; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ArrayInitializerExpression, fs.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal("{ }", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariables() { var text = "class a { b c, d, e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.Null(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.Null(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariablesAndInitializers() { var text = "class a { b c = x, d = y, e = z; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("x", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.NotNull(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[1].Initializer.Value); Assert.Equal("y", fs.Declaration.Variables[1].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.NotNull(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[2].Initializer.Value); Assert.Equal("z", fs.Declaration.Variables[2].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFixedField() { var text = "class a { fixed b c[10]; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.FixedKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].ArgumentList); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.OpenBracketToken); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.CloseBracketToken); Assert.Equal(1, fs.Declaration.Variables[0].ArgumentList.Arguments.Count); Assert.Equal("10", fs.Declaration.Variables[0].ArgumentList.Arguments[0].ToString()); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassProperty() { var text = "class a { b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithRefReturn() { var text = "class a { ref b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassPropertyWithRefReadonlyReturn() { var text = "class a { ref readonly b c { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBuiltInTypes() { TestClassPropertyWithBuiltInType(SyntaxKind.BoolKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.SByteKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.IntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UIntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.LongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ULongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.FloatKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.StringKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.CharKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassPropertyWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal(typeText, ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBodies() { var text = "class a { b c { get { } set { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassAutoPropertyWithInitializer() { var text = "class a { b c { get; set; } = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotNull(ps.Initializer); Assert.NotNull(ps.Initializer.Value); Assert.Equal("d", ps.Initializer.Value.ToString()); } [Fact] public void InitializerOnNonAutoProp() { var text = "class C { int P { set {} } = 0; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.Errors().Length); } [Fact] public void TestClassPropertyOrEventWithValue() { TestClassPropertyWithValue(SyntaxKind.GetAccessorDeclaration, SyntaxKind.GetKeyword, SyntaxKind.IdentifierToken); TestClassPropertyWithValue(SyntaxKind.SetAccessorDeclaration, SyntaxKind.SetKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.AddAccessorDeclaration, SyntaxKind.AddKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.RemoveAccessorDeclaration, SyntaxKind.RemoveKeyword, SyntaxKind.IdentifierToken); } private void TestClassPropertyWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { bool isEvent = accessorKeyword == SyntaxKind.AddKeyword || accessorKeyword == SyntaxKind.RemoveKeyword; var text = "class a { " + (isEvent ? "event" : string.Empty) + " b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(isEvent ? SyntaxKind.EventDeclaration : SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, ps.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = ps.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, es.Expression.Kind()); var bx = (AssignmentExpressionSyntax)es.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassEventWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { var text = "class a { event b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(1, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, es.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = es.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var xs = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(xs.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, xs.Expression.Kind()); var bx = (AssignmentExpressionSyntax)xs.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(mod, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } private void TestClassPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { b c { " + SyntaxFacts.GetText(mod) + " get { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassPropertyWithAccessorModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassPropertyExplicit() { var text = "class a { b I.c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassEventProperty() { var text = "class a { event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } private void TestClassEventPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(1, es.Modifiers.Count); Assert.Equal(mod, es.Modifiers[0].Kind()); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); } private void TestClassEventPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { event b c { " + SyntaxFacts.GetText(mod) + " add { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(SyntaxKind.EventKeyword, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithAccessorModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassEventPropertyWithModifier(SyntaxKind.NewKeyword); TestClassEventPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassEventPropertyExplicit() { var text = "class a { event b I.c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.NotNull(es.ExplicitInterfaceSpecifier); Assert.Equal("I", es.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassIndexer() { var text = "class a { b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithRefReturn() { var text = "class a { ref b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassIndexerWithRefReadonlyReturn() { var text = "class a { ref readonly b this[c d] { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithMultipleParameters() { var text = "class a { b this[c d, e f] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerExplicit() { var text = "class a { b I.this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal(".", ps.ExplicitInterfaceSpecifier.DotToken.ToString()); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } private void TestClassBinaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } [Fact] public void TestClassBinaryOperatorMethods() { TestClassBinaryOperatorMethod(SyntaxKind.PlusToken); TestClassBinaryOperatorMethod(SyntaxKind.MinusToken); TestClassBinaryOperatorMethod(SyntaxKind.AsteriskToken); TestClassBinaryOperatorMethod(SyntaxKind.SlashToken); TestClassBinaryOperatorMethod(SyntaxKind.PercentToken); TestClassBinaryOperatorMethod(SyntaxKind.CaretToken); TestClassBinaryOperatorMethod(SyntaxKind.AmpersandToken); TestClassBinaryOperatorMethod(SyntaxKind.BarToken); // TestClassBinaryOperatorMethod(SyntaxKind.AmpersandAmpersandToken); // TestClassBinaryOperatorMethod(SyntaxKind.BarBarToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanLessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.EqualsEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.ExclamationEqualsToken); } [Fact] public void TestClassRightShiftOperatorMethod() { var text = "class a { b operator >> (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } private void TestClassUnaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassUnaryOperatorMethods() { TestClassUnaryOperatorMethod(SyntaxKind.PlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TildeToken); TestClassUnaryOperatorMethod(SyntaxKind.ExclamationToken); TestClassUnaryOperatorMethod(SyntaxKind.PlusPlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusMinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TrueKeyword); TestClassUnaryOperatorMethod(SyntaxKind.FalseKeyword); } [Fact] public void TestClassImplicitConversionOperatorMethod() { var text = "class a { implicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ImplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassExplicitConversionOperatorMethod() { var text = "class a { explicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ExplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestNamespaceDeclarationsBadNames() { var text = "namespace A::B { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.AliasQualifiedName, ns.Name.Kind()); text = "namespace A<B> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); text = "namespace A<,> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); } [Fact] public void TestNamespaceDeclarationsBadNames1() { var text = @"namespace A::B { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7000: Unexpected use of an aliased name // namespace A::B { } Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "A::B").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames2() { var text = @"namespace A<B> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<B> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<B>").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames3() { var text = @"namespace A<,> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<,> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<,>").WithLocation(1, 11)); } [WorkItem(537690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537690")] [Fact] public void TestMissingSemicolonAfterListInitializer() { var text = @"using System; using System.Linq; class Program { static void Main() { var r = new List<int>() { 3, 3 } var s = 2; } } "; var file = this.ParseFile(text); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestPartialPartial() { var text = @" partial class PartialPartial { int i = 1; partial partial void PM(); partial partial void PM() { i = 0; } static int Main() { PartialPartial t = new PartialPartial(); t.PM(); return t.i; } } "; // These errors aren't great. Ideally we can improve things in the future. CreateCompilation(text).VerifyDiagnostics( // (5,13): error CS1525: Invalid expression term 'partial' // partial partial void PM(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(5, 13), // (5,13): error CS1002: ; expected // partial partial void PM(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(5, 13), // (6,13): error CS1525: Invalid expression term 'partial' // partial partial void PM() Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(6, 13), // (6,13): error CS1002: ; expected // partial partial void PM() Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(6, 13), // (6,13): error CS0102: The type 'PartialPartial' already contains a definition for '' // partial partial void PM() Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("PartialPartial", "").WithLocation(6, 13), // (5,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(5, 5), // (6,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(6, 5)); } [Fact] public void TestPartialEnum() { var text = @"partial enum E{}"; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (1,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(1, 1), // (1,14): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "E").WithLocation(1, 14)); } [WorkItem(539120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539120")] [Fact] public void TestEscapedConstructor() { var text = @" class @class { public @class() { } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [WorkItem(536956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536956")] [Fact] public void TestAnonymousMethodWithDefaultParameter() { var text = @" delegate void F(int x); class C { void M() { F f = delegate (int x = 0) { }; } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); CreateCompilation(text).VerifyDiagnostics( // (5,28): error CS1065: Default values are not valid in this context. // F f = delegate (int x = 0) { }; Diagnostic(ErrorCode.ERR_DefaultValueNotAllowed, "=").WithLocation(5, 28)); } [WorkItem(537865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537865")] [Fact] public void RegressIfDevTrueUnicode() { var text = @" class P { static void Main() { #if tru\u0065 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierDefn() { var text = @" //130 chars (max is 128) #define A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 class P { static void Main() { //first 128 chars of defined value #if A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierUse() { var text = @" //128 chars (max) #define A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 class P { static void Main() { //defined value + two chars (larger than max) #if A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } //Expects a single class, containing a single method, containing a single statement. //Presumably, the statement depends on a conditional compilation directive. private void TestConditionalCompilation(string text, string desiredText, string undesiredText) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToFullString()); var @class = (TypeDeclarationSyntax)file.Members[0]; var mainMethod = (MethodDeclarationSyntax)@class.Members[0]; Assert.NotNull(mainMethod.Body); Assert.Equal(1, mainMethod.Body.Statements.Count); var statement = mainMethod.Body.Statements[0]; var stmtText = statement.ToString(); //make sure we compiled out the right statement Assert.Contains(desiredText, stmtText, StringComparison.Ordinal); Assert.DoesNotContain(undesiredText, stmtText, StringComparison.Ordinal); } private void TestError(string text, ErrorCode error) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Errors().Length); Assert.Equal(error, (ErrorCode)file.Errors()[0].Code); } [Fact] public void TestBadlyPlacedParams() { var text1 = @" class C { void M(params int[] i, int j) {} }"; var text2 = @" class C { void M(__arglist, int j) {} }"; CreateCompilation(text1).VerifyDiagnostics( // (4,11): error CS0231: A params parameter must be the last parameter in a formal parameter list // void M(params int[] i, int j) {} Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] i").WithLocation(4, 11)); CreateCompilation(text2).VerifyDiagnostics( // (4,11): error CS0257: An __arglist parameter must be the last parameter in a formal parameter list // void M(__arglist, int j) {} Diagnostic(ErrorCode.ERR_VarargsLast, "__arglist").WithLocation(4, 11)); } [Fact] public void ValidFixedBufferTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; internal fixed int _Type3[10]; private fixed short _Type4[10]; unsafe fixed long _Type5[10]; new fixed char _Type6[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesMultipleDeclarationsOnSameLine() { var text = @" unsafe struct s { public fixed bool _Type1[10], _Type2[10], _Type3[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesWithCountFromConstantOrLiteral() { var text = @" unsafe struct s { public const int abc = 10; public fixed bool _Type1[abc]; public fixed bool _Type2[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesAllValidTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; public fixed byte _Type12[10]; public fixed int _Type2[10]; public fixed short _Type3[10]; public fixed long _Type4[10]; public fixed char _Type5[10]; public fixed sbyte _Type6[10]; public fixed ushort _Type7[10]; public fixed uint _Type8[10]; public fixed ulong _Type9[10]; public fixed float _Type10[10]; public fixed double _Type11[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void CS0071_01() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_02() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_03() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P10"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_04() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(4826, "https://github.com/dotnet/roslyn/pull/4826")] public void NonAccessorAfterIncompleteProperty() { UsingTree(@" class C { int A { get { return this. public int B; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleArgument01() { var text = @" class C1 { static (T, T) Test1<T>(int a, (byte, byte) arg0) { return default((T, T)); } static (T, T) Test2<T>(ref (byte, byte) arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void TupleArgument02() { var text = @" class C1 { static (T, T) Test3<T>((byte, byte) arg0) { return default((T, T)); } (T, T) Test3<T>((byte a, byte b)[] arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] [WorkItem(13578, "https://github.com/dotnet/roslyn/issues/13578")] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedCtorDtorProp() { UsingTree(@" class C { C() : base() => M(); C() => M(); ~C() => M(); int P { set => M(); } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BaseConstructorInitializer); { N(SyntaxKind.ColonToken); N(SyntaxKind.BaseKeyword); N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.DestructorDeclaration); { N(SyntaxKind.TildeToken); N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void ParseOutVar() { var tree = UsingTree(@" class C { void Goo() { M(out var x); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList1() { var tree = UsingTree(@" class C<T> : where "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList2() { var tree = UsingTree(@" class C<T> : where T "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList3() { var tree = UsingTree(@" class C<T> : where T : "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); M(SyntaxKind.TypeConstraint); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList4() { var tree = UsingTree(@" class C<T> : where T : X "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get() { var code = @" class Program { public int P { ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get_SecondModifier() { var code = @" class Program { public int P { abstract ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set() { var code = @" class Program { public int P { ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set_SecondModifier() { var code = @" class Program { public int P { abstract ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref() { var code = @" public class Program { event System.EventHandler E { ref add => throw null; ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(7, 9)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref_SecondModifier() { var code = @" public class Program { event System.EventHandler E { abstract ref add => throw null; abstract ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(7, 9)); } [Fact] public void NullableClassConstraint_01() { var tree = UsingNode(@" class C<T> where T : class {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_02() { var tree = UsingNode(@" class C<T> where T : struct {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_03() { var tree = UsingNode(@" class C<T> where T : class? {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_04() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_05() { var tree = UsingNode(@" class C<T> where T : class? {} ", TestOptions.Regular7_3); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_06() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular7_3, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList1() { var tree = UsingNode(@" class B : A<int { } ", TestOptions.Regular7_3, // (2,16): error CS1003: Syntax error, '>' expected // class B : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "{").WithLocation(2, 16)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot1() { var text = @"namespace a..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList2() { var tree = UsingNode(@" class B<X, Y> : A<int where X : Y { } ", TestOptions.Regular7_3, // (2,22): error CS1003: Syntax error, '>' expected // class B<X, Y> : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "").WithLocation(2, 22)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void TestExtraneousColonInBaseList() { var tree = UsingNode(@" class A : B : C { } ", TestOptions.Regular7_3, // (2,13): error CS1514: { expected // class A : B : C Diagnostic(ErrorCode.ERR_LbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1513: } expected // class A : B : C Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1022: Type or namespace definition, or end-of-file expected // class A : B : C Diagnostic(ErrorCode.ERR_EOFExpected, ":").WithLocation(2, 13), // (2,15): error CS0116: A namespace cannot directly contain members such as fields or methods // class A : B : C Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "C").WithLocation(2, 15), // (3,1): error CS8370: Feature 'top-level statements' is not available in C# 7.3. Please use language version 9.0 or greater. // { Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, @"{ }").WithArguments("top-level statements", "9.0").WithLocation(3, 1), // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // { Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"{ }").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot2() { var text = @"namespace a ..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // ..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot3() { var text = @"namespace a.. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a.. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot4() { var text = @"namespace a .. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // .. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_01(bool useCSharp8) { UsingNode( @"class C<T> where T : default { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.Regular9, useCSharp8 ? new[] { // (1,22): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // class C<T> where T : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(1, 22) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_02() { UsingNode( @"class C<T, U> where T : default where U : default { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_03(bool useCSharp8) { UsingNode( @"class C<T, U> where T : struct, default where U : default, class { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.Regular9, useCSharp8 ? new[] { // (2,23): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // where T : struct, default Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(2, 23), // (3,15): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // where U : default, class { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(3, 15) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_04() { UsingNode( @"class C<T, U> where T : struct default where U : default class { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DeclarationParsingTests : ParsingTests { public DeclarationParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular); } [Fact] public void TestExternAlias() { var text = "extern alias a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Externs.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ea = file.Externs[0]; Assert.NotEqual(default, ea.ExternKeyword); Assert.Equal(SyntaxKind.ExternKeyword, ea.ExternKeyword.Kind()); Assert.NotEqual(default, ea.AliasKeyword); Assert.Equal(SyntaxKind.AliasKeyword, ea.AliasKeyword.Kind()); Assert.False(ea.AliasKeyword.IsMissing); Assert.NotEqual(default, ea.Identifier); Assert.Equal("a", ea.Identifier.ToString()); Assert.NotEqual(default, ea.SemicolonToken); } [Fact] public void TestUsing() { var text = "using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Null(ud.Alias); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStatic() { var text = "using static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticInWrongOrder() { var text = "static using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToFullString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_NamespaceUnexpected, errors[0].Code); } [Fact] public void TestDuplicateStatic() { var text = "using static static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingNamespace() { var text = "using namespace a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingDottedName() { var text = "using a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticDottedName() { var text = "using static a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticGenericName() { var text = "using static a<int?>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a<int?>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasName() { var text = "using a = b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasGenericName() { var text = "using a = b<c>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b<c>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestGlobalAttribute() { var text = "[assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Verbatim() { var text = "[@assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@assembly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Escape() { var text = @"[as\u0073embly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal(@"as\u0073embly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute() { var text = "[module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.ModuleKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute_Verbatim() { var text = "[@module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Module, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithParentheses() { var text = "[assembly:a()]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.AssemblyKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(0, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleArguments() { var text = "[assembly:a(b, c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(2, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[1].ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithNamedArguments() { var text = "[assembly:a(b = c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(1, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b = c", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.EqualsToken); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].Expression); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[0].Expression.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleAttributes() { var text = "[assembly:a, b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(2, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotNull(ad.Attributes[1].Name); Assert.Equal("b", ad.Attributes[1].Name.ToString()); Assert.Null(ad.Attributes[1].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestMultipleGlobalAttributeDeclarations() { var text = "[assembly:a] [assembly:b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(2, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); ad = (AttributeListSyntax)file.AttributeLists[1]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("b", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestNamespace() { var text = "namespace a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespace() { var text = "namespace a;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithDottedName() { var text = "namespace a.b.c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a.b.c", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithUsing() { var text = "namespace a { using b.c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b.c;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespaceWithUsing() { var text = "namespace a; using b.c;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b.c;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithExternAlias() { var text = "namespace a { extern alias b; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Externs.Count); Assert.Equal("extern alias b;", ns.Externs[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestFileScopedNamespaceWithExternAlias() { var text = "namespace a; extern alias b;"; var file = this.ParseFile(text, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.FileScopedNamespaceDeclaration, file.Members[0].Kind()); var ns = (FileScopedNamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.SemicolonToken); Assert.Equal(1, ns.Externs.Count); Assert.Equal("extern alias b;", ns.Externs[0].ToString()); Assert.Equal(0, ns.Members.Count); } [Fact] public void TestNamespaceWithExternAliasFollowingUsingBad() { var text = "namespace a { using b; extern alias c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Externs.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithNestedNamespace() { var text = "namespace a { namespace b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(1, ns.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, ns.Members[0].Kind()); var ns2 = (NamespaceDeclarationSyntax)ns.Members[0]; Assert.NotEqual(default, ns2.NamespaceKeyword); Assert.NotNull(ns2.Name); Assert.Equal("b", ns2.Name.ToString()); Assert.NotEqual(default, ns2.OpenBraceToken); Assert.Equal(0, ns2.Usings.Count); Assert.Equal(0, ns2.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestClass() { var text = "class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPublic() { var text = "public class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithInternal() { var text = "internal class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStatic() { var text = "static class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithSealed() { var text = "sealed class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.SealedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAbstract() { var text = "abstract class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.AbstractKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPartial() { var text = "partial class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAttribute() { var text = "[attr] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributes() { var text = "[attr1] [attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, cs.AttributeLists.Count); Assert.Equal("[attr1]", cs.AttributeLists[0].ToString()); Assert.Equal("[attr2]", cs.AttributeLists[1].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributesInAList() { var text = "[attr1, attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr1, attr2]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithBaseType() { var text = "class a : b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(1, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleBases() { var text = "class a : b, c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("c", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithTypeConstraintBound() { var text = "class a<b> where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNonGenericClassWithTypeConstraintBound() { var text = "class a where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,9): error CS0080: Constraints are not allowed on non-generic declarations // class a where b : c { } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 9)); } [Fact] public void TestNonGenericMethodWithTypeConstraintBound() { var text = "class a { void M() where b : c { } }"; CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,20): error CS0080: Constraints are not allowed on non-generic declarations // class a { void M() where b : c { } } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 20)); } [Fact] public void TestClassWithNewConstraintBound() { var text = "class a<b> where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithClassConstraintBound() { var text = "class a<b> where b : class { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStructConstraintBound() { var text = "class a<b> where b : struct { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.StructConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.StructKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraintBounds() { var text = "class a<b> where b : class, c, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints() { var text = "class a<b> where b : c where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.False(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints001() { var text = "class a<b> where b : c where b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(2, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleConstraints002() { var text = "class a<b> where b : c where { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.True(cs.ConstraintClauses[1].Name.IsMissing); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleBasesAndConstraints() { var text = "class a<b> : c, d where b : class, e, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("c", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("d", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("e", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestInterface() { var text = "interface a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterface() { var text = "interface A<B> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<B>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(0, gn.Parameters[0].AttributeLists.Count); Assert.Equal(SyntaxKind.None, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Equal("B", gn.Parameters[0].Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterfaceWithAttributesAndVariance() { var text = "interface A<[B] out C> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<[B] out C>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(1, gn.Parameters[0].AttributeLists.Count); Assert.Equal("B", gn.Parameters[0].AttributeLists[0].Attributes[0].Name.ToString()); Assert.NotEqual(default, gn.Parameters[0].VarianceKeyword); Assert.Equal(SyntaxKind.OutKeyword, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestStruct() { var text = "struct a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.StructKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedClass() { var text = "class a { class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPrivateClass() { var text = "class a { private class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PrivateKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedClass() { var text = "class a { protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedInternalClass() { var text = "class a { protected internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalProtectedClass() { var text = "class a { internal protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPublicClass() { var text = "class a { public class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalClass() { var text = "class a { internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestDelegate() { var text = "delegate a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefReturnType() { var text = "delegate ref a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestDelegateWithRefReadonlyReturnType() { var text = "delegate ref readonly a b();"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref readonly a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInReturnTypes() { TestDelegateWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInReturnType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate " + typeText + " b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal(typeText, ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInParameterTypes() { TestDelegateWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInParameterType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate a b(" + typeText + " c);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameter() { var text = "delegate a b(c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithMultipleParameters() { var text = "delegate a b(c d, e f);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ds.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[1].Type); Assert.Equal("e", ds.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ds.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefParameter() { var text = "delegate a b(ref c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.RefKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithOutParameter() { var text = "delegate a b(out c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.OutKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParamsParameter() { var text = "delegate a b(params c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.ParamsKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithArgListParameter() { var text = "delegate a b(__arglist);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ds.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameterAttribute() { var text = "delegate a b([attr] c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal("[attr]", ds.ParameterList.Parameters[0].AttributeLists[0].ToString()); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestNestedDelegate() { var text = "class a { delegate b c(); }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, cs.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("b", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("c", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestClassMethod() { var text = "class a { b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRefReturn() { var text = "class a { ref b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonlyReturn() { var text = "class a { ref readonly b X() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref readonly b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRef() { var text = "class a { ref }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonly() { var text = "class a { ref readonly }"; var file = this.ParseFile(text, parseOptions: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } private void TestClassMethodModifiers(params SyntaxKind[] modifiers) { var text = "class a { " + string.Join(" ", modifiers.Select(SyntaxFacts.GetText)) + " b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(modifiers.Length, ms.Modifiers.Count); for (int i = 0; i < modifiers.Length; ++i) { Assert.Equal(modifiers[i], ms.Modifiers[i].Kind()); } Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodAccessModes() { TestClassMethodModifiers(SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.PrivateKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword); TestClassMethodModifiers(SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodModifiersOrder() { TestClassMethodModifiers(SyntaxKind.PublicKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodWithPartial() { var text = "class a { partial void M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructMethodWithReadonly() { var text = "struct a { readonly void M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestReadOnlyRefReturning() { var text = "struct a { readonly ref readonly int M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.RefType, ms.ReturnType.Kind()); var rt = (RefTypeSyntax)ms.ReturnType; Assert.Equal(SyntaxKind.RefKeyword, rt.RefKeyword.Kind()); Assert.Equal(SyntaxKind.ReadOnlyKeyword, rt.ReadOnlyKeyword.Kind()); Assert.Equal("int", rt.Type.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructExpressionPropertyWithReadonly() { var text = "struct a { readonly int M => 42; }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(1, propertySyntax.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, propertySyntax.Modifiers[0].Kind()); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("M", propertySyntax.Identifier.ToString()); Assert.NotNull(propertySyntax.ExpressionBody); Assert.NotEqual(SyntaxKind.None, propertySyntax.ExpressionBody.ArrowToken.Kind()); Assert.NotNull(propertySyntax.ExpressionBody.Expression); Assert.Equal(SyntaxKind.SemicolonToken, propertySyntax.SemicolonToken.Kind()); } [Fact] public void TestStructGetterPropertyWithReadonly() { var text = "struct a { int P { readonly get { return 42; } } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(0, propertySyntax.Modifiers.Count); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("P", propertySyntax.Identifier.ToString()); var accessors = propertySyntax.AccessorList.Accessors; Assert.Equal(1, accessors.Count); Assert.Equal(1, accessors[0].Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, accessors[0].Modifiers[0].Kind()); } [Fact] public void TestStructBadExpressionProperty() { var text = @"public struct S { public int P readonly => 0; } "; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemicolonExpected, (ErrorCode)file.Errors()[0].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[1].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[2].Code); } [Fact] public void TestClassMethodWithParameter() { var text = "class a { b X(c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithMultipleParameters() { var text = "class a { b X(c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ms.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[1].Type); Assert.Equal("e", ms.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ms.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } private void TestClassMethodWithParameterModifier(SyntaxKind mod) { var text = "class a { b X(" + SyntaxFacts.GetText(mod) + " c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(mod, ms.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithParameterModifiers() { TestClassMethodWithParameterModifier(SyntaxKind.RefKeyword); TestClassMethodWithParameterModifier(SyntaxKind.OutKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ParamsKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ThisKeyword); } [Fact] public void TestClassMethodWithArgListParameter() { var text = "class a { b X(__arglist) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ms.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal(SyntaxKind.ArgListKeyword, ms.ParameterList.Parameters[0].Identifier.Kind()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInReturnTypes() { TestClassMethodWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInReturnType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal(typeText, ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInParameterTypes() { TestClassMethodWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInParameterType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { b X(" + typeText + " c) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethod() { var text = "class a { b<c> M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b<c>", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethodWithTypeConstraintBound() { var text = "class a { b X<c>() where b : d { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.NotNull(ms.TypeParameterList); Assert.Equal("X", ms.Identifier.ToString()); Assert.Equal("<c>", ms.TypeParameterList.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses.Count); Assert.NotEqual(default, ms.ConstraintClauses[0].WhereKeyword); Assert.NotNull(ms.ConstraintClauses[0].Name); Assert.Equal("b", ms.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, ms.ConstraintClauses[0].ColonToken); Assert.False(ms.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, ms.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)ms.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("d", typeBound.Type.ToString()); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [WorkItem(899685, "DevDiv/Personal")] [Fact] public void TestGenericClassConstructor() { var text = @" class Class1<T>{ public Class1() { } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); // verify that we can roundtrip Assert.Equal(text, file.ToFullString()); // verify that we don't produce any errors Assert.Equal(0, file.Errors().Length); } [Fact] public void TestClassConstructor() { var text = "class a { a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } private void TestClassConstructorWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(1, cn.Modifiers.Count); Assert.Equal(mod, cn.Modifiers[0].Kind()); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassConstructorWithModifiers() { TestClassConstructorWithModifier(SyntaxKind.PublicKeyword); TestClassConstructorWithModifier(SyntaxKind.PrivateKeyword); TestClassConstructorWithModifier(SyntaxKind.ProtectedKeyword); TestClassConstructorWithModifier(SyntaxKind.InternalKeyword); TestClassConstructorWithModifier(SyntaxKind.StaticKeyword); } [Fact] public void TestClassDestructor() { var text = "class a { ~a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DestructorDeclaration, cs.Members[0].Kind()); var cn = (DestructorDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, cn.TildeToken); Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassField() { var text = "class a { b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithBuiltInTypes() { TestClassFieldWithBuiltInType(SyntaxKind.BoolKeyword); TestClassFieldWithBuiltInType(SyntaxKind.SByteKeyword); TestClassFieldWithBuiltInType(SyntaxKind.IntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UIntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.LongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ULongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.FloatKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassFieldWithBuiltInType(SyntaxKind.StringKeyword); TestClassFieldWithBuiltInType(SyntaxKind.CharKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassFieldWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal(typeText, fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } private void TestClassFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldModifiers() { TestClassFieldModifier(SyntaxKind.PublicKeyword); TestClassFieldModifier(SyntaxKind.PrivateKeyword); TestClassFieldModifier(SyntaxKind.ProtectedKeyword); TestClassFieldModifier(SyntaxKind.InternalKeyword); TestClassFieldModifier(SyntaxKind.StaticKeyword); TestClassFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassFieldModifier(SyntaxKind.VolatileKeyword); TestClassFieldModifier(SyntaxKind.ExternKeyword); } private void TestClassEventFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventFieldDeclaration, cs.Members[0].Kind()); var fs = (EventFieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotEqual(default, fs.EventKeyword); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassEventFieldModifiers() { TestClassEventFieldModifier(SyntaxKind.PublicKeyword); TestClassEventFieldModifier(SyntaxKind.PrivateKeyword); TestClassEventFieldModifier(SyntaxKind.ProtectedKeyword); TestClassEventFieldModifier(SyntaxKind.InternalKeyword); TestClassEventFieldModifier(SyntaxKind.StaticKeyword); TestClassEventFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassEventFieldModifier(SyntaxKind.VolatileKeyword); TestClassEventFieldModifier(SyntaxKind.ExternKeyword); } [Fact] public void TestClassConstField() { var text = "class a { const b c = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.ConstKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("d", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithInitializer() { var text = "class a { b c = e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("e", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithArrayInitializer() { var text = "class a { b c = { }; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ArrayInitializerExpression, fs.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal("{ }", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariables() { var text = "class a { b c, d, e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.Null(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.Null(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariablesAndInitializers() { var text = "class a { b c = x, d = y, e = z; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("x", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.NotNull(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[1].Initializer.Value); Assert.Equal("y", fs.Declaration.Variables[1].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.NotNull(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[2].Initializer.Value); Assert.Equal("z", fs.Declaration.Variables[2].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFixedField() { var text = "class a { fixed b c[10]; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.FixedKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].ArgumentList); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.OpenBracketToken); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.CloseBracketToken); Assert.Equal(1, fs.Declaration.Variables[0].ArgumentList.Arguments.Count); Assert.Equal("10", fs.Declaration.Variables[0].ArgumentList.Arguments[0].ToString()); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassProperty() { var text = "class a { b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithRefReturn() { var text = "class a { ref b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassPropertyWithRefReadonlyReturn() { var text = "class a { ref readonly b c { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBuiltInTypes() { TestClassPropertyWithBuiltInType(SyntaxKind.BoolKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.SByteKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.IntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UIntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.LongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ULongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.FloatKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.StringKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.CharKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassPropertyWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal(typeText, ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBodies() { var text = "class a { b c { get { } set { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassAutoPropertyWithInitializer() { var text = "class a { b c { get; set; } = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotNull(ps.Initializer); Assert.NotNull(ps.Initializer.Value); Assert.Equal("d", ps.Initializer.Value.ToString()); } [Fact] public void InitializerOnNonAutoProp() { var text = "class C { int P { set {} } = 0; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.Errors().Length); } [Fact] public void TestClassPropertyOrEventWithValue() { TestClassPropertyWithValue(SyntaxKind.GetAccessorDeclaration, SyntaxKind.GetKeyword, SyntaxKind.IdentifierToken); TestClassPropertyWithValue(SyntaxKind.SetAccessorDeclaration, SyntaxKind.SetKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.AddAccessorDeclaration, SyntaxKind.AddKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.RemoveAccessorDeclaration, SyntaxKind.RemoveKeyword, SyntaxKind.IdentifierToken); } private void TestClassPropertyWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { bool isEvent = accessorKeyword == SyntaxKind.AddKeyword || accessorKeyword == SyntaxKind.RemoveKeyword; var text = "class a { " + (isEvent ? "event" : string.Empty) + " b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(isEvent ? SyntaxKind.EventDeclaration : SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, ps.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = ps.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, es.Expression.Kind()); var bx = (AssignmentExpressionSyntax)es.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassEventWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { var text = "class a { event b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(1, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, es.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = es.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var xs = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(xs.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, xs.Expression.Kind()); var bx = (AssignmentExpressionSyntax)xs.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(mod, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } private void TestClassPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { b c { " + SyntaxFacts.GetText(mod) + " get { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassPropertyWithAccessorModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassPropertyExplicit() { var text = "class a { b I.c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassEventProperty() { var text = "class a { event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } private void TestClassEventPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(1, es.Modifiers.Count); Assert.Equal(mod, es.Modifiers[0].Kind()); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); } private void TestClassEventPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { event b c { " + SyntaxFacts.GetText(mod) + " add { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(SyntaxKind.EventKeyword, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithAccessorModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassEventPropertyWithModifier(SyntaxKind.NewKeyword); TestClassEventPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassEventPropertyExplicit() { var text = "class a { event b I.c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.NotNull(es.ExplicitInterfaceSpecifier); Assert.Equal("I", es.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassIndexer() { var text = "class a { b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithRefReturn() { var text = "class a { ref b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassIndexerWithRefReadonlyReturn() { var text = "class a { ref readonly b this[c d] { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithMultipleParameters() { var text = "class a { b this[c d, e f] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerExplicit() { var text = "class a { b I.this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal(".", ps.ExplicitInterfaceSpecifier.DotToken.ToString()); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } private void TestClassBinaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } [Fact] public void TestClassBinaryOperatorMethods() { TestClassBinaryOperatorMethod(SyntaxKind.PlusToken); TestClassBinaryOperatorMethod(SyntaxKind.MinusToken); TestClassBinaryOperatorMethod(SyntaxKind.AsteriskToken); TestClassBinaryOperatorMethod(SyntaxKind.SlashToken); TestClassBinaryOperatorMethod(SyntaxKind.PercentToken); TestClassBinaryOperatorMethod(SyntaxKind.CaretToken); TestClassBinaryOperatorMethod(SyntaxKind.AmpersandToken); TestClassBinaryOperatorMethod(SyntaxKind.BarToken); // TestClassBinaryOperatorMethod(SyntaxKind.AmpersandAmpersandToken); // TestClassBinaryOperatorMethod(SyntaxKind.BarBarToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanLessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.EqualsEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.ExclamationEqualsToken); } [Fact] public void TestClassRightShiftOperatorMethod() { var text = "class a { b operator >> (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } private void TestClassUnaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassUnaryOperatorMethods() { TestClassUnaryOperatorMethod(SyntaxKind.PlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TildeToken); TestClassUnaryOperatorMethod(SyntaxKind.ExclamationToken); TestClassUnaryOperatorMethod(SyntaxKind.PlusPlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusMinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TrueKeyword); TestClassUnaryOperatorMethod(SyntaxKind.FalseKeyword); } [Fact] public void TestClassImplicitConversionOperatorMethod() { var text = "class a { implicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ImplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassExplicitConversionOperatorMethod() { var text = "class a { explicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ExplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestNamespaceDeclarationsBadNames() { var text = "namespace A::B { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.AliasQualifiedName, ns.Name.Kind()); text = "namespace A<B> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); text = "namespace A<,> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); } [Fact] public void TestNamespaceDeclarationsBadNames1() { var text = @"namespace A::B { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7000: Unexpected use of an aliased name // namespace A::B { } Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "A::B").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames2() { var text = @"namespace A<B> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<B> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<B>").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames3() { var text = @"namespace A<,> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<,> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<,>").WithLocation(1, 11)); } [WorkItem(537690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537690")] [Fact] public void TestMissingSemicolonAfterListInitializer() { var text = @"using System; using System.Linq; class Program { static void Main() { var r = new List<int>() { 3, 3 } var s = 2; } } "; var file = this.ParseFile(text); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestPartialPartial() { var text = @" partial class PartialPartial { int i = 1; partial partial void PM(); partial partial void PM() { i = 0; } static int Main() { PartialPartial t = new PartialPartial(); t.PM(); return t.i; } } "; // These errors aren't great. Ideally we can improve things in the future. CreateCompilation(text).VerifyDiagnostics( // (5,13): error CS1525: Invalid expression term 'partial' // partial partial void PM(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(5, 13), // (5,13): error CS1002: ; expected // partial partial void PM(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(5, 13), // (6,13): error CS1525: Invalid expression term 'partial' // partial partial void PM() Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(6, 13), // (6,13): error CS1002: ; expected // partial partial void PM() Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(6, 13), // (6,13): error CS0102: The type 'PartialPartial' already contains a definition for '' // partial partial void PM() Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("PartialPartial", "").WithLocation(6, 13), // (5,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(5, 5), // (6,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(6, 5)); } [Fact] public void TestPartialEnum() { var text = @"partial enum E{}"; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (1,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(1, 1), // (1,14): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "E").WithLocation(1, 14)); } [WorkItem(539120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539120")] [Fact] public void TestEscapedConstructor() { var text = @" class @class { public @class() { } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [WorkItem(536956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536956")] [Fact] public void TestAnonymousMethodWithDefaultParameter() { var text = @" delegate void F(int x); class C { void M() { F f = delegate (int x = 0) { }; } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); CreateCompilation(text).VerifyDiagnostics( // (5,28): error CS1065: Default values are not valid in this context. // F f = delegate (int x = 0) { }; Diagnostic(ErrorCode.ERR_DefaultValueNotAllowed, "=").WithLocation(5, 28)); } [WorkItem(537865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537865")] [Fact] public void RegressIfDevTrueUnicode() { var text = @" class P { static void Main() { #if tru\u0065 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierDefn() { var text = @" //130 chars (max is 128) #define A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 class P { static void Main() { //first 128 chars of defined value #if A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierUse() { var text = @" //128 chars (max) #define A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 class P { static void Main() { //defined value + two chars (larger than max) #if A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } //Expects a single class, containing a single method, containing a single statement. //Presumably, the statement depends on a conditional compilation directive. private void TestConditionalCompilation(string text, string desiredText, string undesiredText) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToFullString()); var @class = (TypeDeclarationSyntax)file.Members[0]; var mainMethod = (MethodDeclarationSyntax)@class.Members[0]; Assert.NotNull(mainMethod.Body); Assert.Equal(1, mainMethod.Body.Statements.Count); var statement = mainMethod.Body.Statements[0]; var stmtText = statement.ToString(); //make sure we compiled out the right statement Assert.Contains(desiredText, stmtText, StringComparison.Ordinal); Assert.DoesNotContain(undesiredText, stmtText, StringComparison.Ordinal); } private void TestError(string text, ErrorCode error) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Errors().Length); Assert.Equal(error, (ErrorCode)file.Errors()[0].Code); } [Fact] public void TestBadlyPlacedParams() { var text1 = @" class C { void M(params int[] i, int j) {} }"; var text2 = @" class C { void M(__arglist, int j) {} }"; CreateCompilation(text1).VerifyDiagnostics( // (4,11): error CS0231: A params parameter must be the last parameter in a formal parameter list // void M(params int[] i, int j) {} Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] i").WithLocation(4, 11)); CreateCompilation(text2).VerifyDiagnostics( // (4,11): error CS0257: An __arglist parameter must be the last parameter in a formal parameter list // void M(__arglist, int j) {} Diagnostic(ErrorCode.ERR_VarargsLast, "__arglist").WithLocation(4, 11)); } [Fact] public void ValidFixedBufferTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; internal fixed int _Type3[10]; private fixed short _Type4[10]; unsafe fixed long _Type5[10]; new fixed char _Type6[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesMultipleDeclarationsOnSameLine() { var text = @" unsafe struct s { public fixed bool _Type1[10], _Type2[10], _Type3[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesWithCountFromConstantOrLiteral() { var text = @" unsafe struct s { public const int abc = 10; public fixed bool _Type1[abc]; public fixed bool _Type2[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesAllValidTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; public fixed byte _Type12[10]; public fixed int _Type2[10]; public fixed short _Type3[10]; public fixed long _Type4[10]; public fixed char _Type5[10]; public fixed sbyte _Type6[10]; public fixed ushort _Type7[10]; public fixed uint _Type8[10]; public fixed ulong _Type9[10]; public fixed float _Type10[10]; public fixed double _Type11[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void CS0071_01() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_02() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_03() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P10"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_04() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(4826, "https://github.com/dotnet/roslyn/pull/4826")] public void NonAccessorAfterIncompleteProperty() { UsingTree(@" class C { int A { get { return this. public int B; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleArgument01() { var text = @" class C1 { static (T, T) Test1<T>(int a, (byte, byte) arg0) { return default((T, T)); } static (T, T) Test2<T>(ref (byte, byte) arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void TupleArgument02() { var text = @" class C1 { static (T, T) Test3<T>((byte, byte) arg0) { return default((T, T)); } (T, T) Test3<T>((byte a, byte b)[] arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] [WorkItem(13578, "https://github.com/dotnet/roslyn/issues/13578")] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedCtorDtorProp() { UsingTree(@" class C { C() : base() => M(); C() => M(); ~C() => M(); int P { set => M(); } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BaseConstructorInitializer); { N(SyntaxKind.ColonToken); N(SyntaxKind.BaseKeyword); N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.DestructorDeclaration); { N(SyntaxKind.TildeToken); N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void ParseOutVar() { var tree = UsingTree(@" class C { void Goo() { M(out var x); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList1() { var tree = UsingTree(@" class C<T> : where "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList2() { var tree = UsingTree(@" class C<T> : where T "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList3() { var tree = UsingTree(@" class C<T> : where T : "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); M(SyntaxKind.TypeConstraint); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList4() { var tree = UsingTree(@" class C<T> : where T : X "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get() { var code = @" class Program { public int P { ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get_SecondModifier() { var code = @" class Program { public int P { abstract ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set() { var code = @" class Program { public int P { ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set_SecondModifier() { var code = @" class Program { public int P { abstract ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref() { var code = @" public class Program { event System.EventHandler E { ref add => throw null; ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(7, 9)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref_SecondModifier() { var code = @" public class Program { event System.EventHandler E { abstract ref add => throw null; abstract ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(7, 9)); } [Fact] public void NullableClassConstraint_01() { var tree = UsingNode(@" class C<T> where T : class {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_02() { var tree = UsingNode(@" class C<T> where T : struct {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_03() { var tree = UsingNode(@" class C<T> where T : class? {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_04() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_05() { var tree = UsingNode(@" class C<T> where T : class? {} ", TestOptions.Regular7_3); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_06() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular7_3, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList1() { var tree = UsingNode(@" class B : A<int { } ", TestOptions.Regular7_3, // (2,16): error CS1003: Syntax error, '>' expected // class B : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "{").WithLocation(2, 16)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot1() { var text = @"namespace a..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList2() { var tree = UsingNode(@" class B<X, Y> : A<int where X : Y { } ", TestOptions.Regular7_3, // (2,22): error CS1003: Syntax error, '>' expected // class B<X, Y> : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "").WithLocation(2, 22)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void TestExtraneousColonInBaseList() { var tree = UsingNode(@" class A : B : C { } ", TestOptions.Regular7_3, // (2,13): error CS1514: { expected // class A : B : C Diagnostic(ErrorCode.ERR_LbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1513: } expected // class A : B : C Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1022: Type or namespace definition, or end-of-file expected // class A : B : C Diagnostic(ErrorCode.ERR_EOFExpected, ":").WithLocation(2, 13), // (2,15): error CS0116: A namespace cannot directly contain members such as fields or methods // class A : B : C Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "C").WithLocation(2, 15), // (3,1): error CS8370: Feature 'top-level statements' is not available in C# 7.3. Please use language version 9.0 or greater. // { Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, @"{ }").WithArguments("top-level statements", "9.0").WithLocation(3, 1), // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // { Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"{ }").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot2() { var text = @"namespace a ..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // ..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot3() { var text = @"namespace a.. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a.. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot4() { var text = @"namespace a .. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // .. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_01(bool useCSharp8) { UsingNode( @"class C<T> where T : default { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.Regular9, useCSharp8 ? new[] { // (1,22): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // class C<T> where T : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(1, 22) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_02() { UsingNode( @"class C<T, U> where T : default where U : default { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_03(bool useCSharp8) { UsingNode( @"class C<T, U> where T : struct, default where U : default, class { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.Regular9, useCSharp8 ? new[] { // (2,23): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // where T : struct, default Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(2, 23), // (3,15): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // where U : default, class { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(3, 15) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_04() { UsingNode( @"class C<T, U> where T : struct default where U : default class { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/Storage/SQLite/v2/Column.cs
// Licensed to the .NET Foundation under one or more 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.SQLite.v2 { internal enum Column { Data, Checksum, } }
// Licensed to the .NET Foundation under one or more 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.SQLite.v2 { internal enum Column { Data, Checksum, } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/MSBuild/MSBuild/Constants/PropertyValues.cs
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal static class PropertyValues { public const string ErrorAndContinue = nameof(ErrorAndContinue); } }
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal static class PropertyValues { public const string ErrorAndContinue = nameof(ErrorAndContinue); } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Portable/Symbols/SubstitutedParameterSymbol.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.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter that has undergone type substitution. ''' </summary> Friend MustInherit Class SubstitutedParameterSymbol Inherits ParameterSymbol Private ReadOnly _originalDefinition As ParameterSymbol Public Shared Function CreateMethodParameter(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedMethodParameterSymbol(container, originalDefinition) End Function Public Shared Function CreatePropertyParameter(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedPropertyParameterSymbol(container, originalDefinition) End Function Protected Sub New(originalDefinition As ParameterSymbol) Debug.Assert(originalDefinition.IsDefinition) _originalDefinition = originalDefinition End Sub Public Overrides ReadOnly Property Name As String Get Return _originalDefinition.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _originalDefinition.MetadataName End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _originalDefinition.Ordinal End Get End Property Public MustOverride Overrides ReadOnly Property ContainingSymbol As Symbol Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return _originalDefinition.ExplicitDefaultConstantValue(inProgress) End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return _originalDefinition.GetAttributes() End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return _originalDefinition.HasExplicitDefaultValue End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return _originalDefinition.IsOptional End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Return _originalDefinition.IsParamArray End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _originalDefinition.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalDefinition.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalDefinition.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _originalDefinition.Type.InternalSubstituteTypeParameters(TypeSubstitution).Type End Get End Property Public Overrides ReadOnly Property IsByRef As Boolean Get Return _originalDefinition.IsByRef End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return _originalDefinition.IsMetadataOut End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return _originalDefinition.IsMetadataIn End Get End Property Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Return _originalDefinition.MarshallingInformation End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return _originalDefinition.HasOptionCompare End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return _originalDefinition.IsIDispatchConstant End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return _originalDefinition.IsIUnknownConstant End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return _originalDefinition.IsCallerLineNumber End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return _originalDefinition.IsCallerMemberName End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return _originalDefinition.IsCallerFilePath End Get End Property Friend NotOverridable Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Return _originalDefinition.CallerArgumentExpressionParameterIndex End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.RefCustomModifiers) End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return _originalDefinition.IsExplicitByRef End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.Type, _originalDefinition.CustomModifiers) End Get End Property Public Overrides ReadOnly Property OriginalDefinition As ParameterSymbol Get Return _originalDefinition End Get End Property Protected MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution Public Overrides Function GetHashCode() As Integer Dim _hash As Integer = _originalDefinition.GetHashCode() Return Hash.Combine(ContainingSymbol, _hash) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SubstitutedParameterSymbol) If other Is Nothing Then Return False End If If Not _originalDefinition.Equals(other._originalDefinition) Then Return False End If If Not ContainingSymbol.Equals(other.ContainingSymbol) Then Return False End If Return True End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function ''' <summary> ''' Represents a method parameter that has undergone type substitution. ''' </summary> Friend Class SubstitutedMethodParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedMethodSymbol Public Sub New(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution End Get End Property End Class ''' <summary> ''' Represents a property parameter that has undergone type substitution. ''' </summary> Private NotInheritable Class SubstitutedPropertyParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedPropertySymbol Public Sub New(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution 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.Globalization Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter that has undergone type substitution. ''' </summary> Friend MustInherit Class SubstitutedParameterSymbol Inherits ParameterSymbol Private ReadOnly _originalDefinition As ParameterSymbol Public Shared Function CreateMethodParameter(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedMethodParameterSymbol(container, originalDefinition) End Function Public Shared Function CreatePropertyParameter(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) As SubstitutedParameterSymbol Return New SubstitutedPropertyParameterSymbol(container, originalDefinition) End Function Protected Sub New(originalDefinition As ParameterSymbol) Debug.Assert(originalDefinition.IsDefinition) _originalDefinition = originalDefinition End Sub Public Overrides ReadOnly Property Name As String Get Return _originalDefinition.Name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return _originalDefinition.MetadataName End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _originalDefinition.Ordinal End Get End Property Public MustOverride Overrides ReadOnly Property ContainingSymbol As Symbol Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get Return _originalDefinition.ExplicitDefaultConstantValue(inProgress) End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return _originalDefinition.GetAttributes() End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return _originalDefinition.HasExplicitDefaultValue End Get End Property Public Overrides ReadOnly Property IsOptional As Boolean Get Return _originalDefinition.IsOptional End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get Return _originalDefinition.IsParamArray End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _originalDefinition.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _originalDefinition.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return _originalDefinition.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get Return _originalDefinition.Type.InternalSubstituteTypeParameters(TypeSubstitution).Type End Get End Property Public Overrides ReadOnly Property IsByRef As Boolean Get Return _originalDefinition.IsByRef End Get End Property Friend Overrides ReadOnly Property IsMetadataOut As Boolean Get Return _originalDefinition.IsMetadataOut End Get End Property Friend Overrides ReadOnly Property IsMetadataIn As Boolean Get Return _originalDefinition.IsMetadataIn End Get End Property Friend Overrides ReadOnly Property MarshallingInformation As MarshalPseudoCustomAttributeData Get Return _originalDefinition.MarshallingInformation End Get End Property Friend Overrides ReadOnly Property HasOptionCompare As Boolean Get Return _originalDefinition.HasOptionCompare End Get End Property Friend Overrides ReadOnly Property IsIDispatchConstant As Boolean Get Return _originalDefinition.IsIDispatchConstant End Get End Property Friend Overrides ReadOnly Property IsIUnknownConstant As Boolean Get Return _originalDefinition.IsIUnknownConstant End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Return _originalDefinition.IsCallerLineNumber End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Return _originalDefinition.IsCallerMemberName End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Return _originalDefinition.IsCallerFilePath End Get End Property Friend NotOverridable Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Return _originalDefinition.CallerArgumentExpressionParameterIndex End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.RefCustomModifiers) End Get End Property Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return _originalDefinition.IsExplicitByRef End Get End Property Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return TypeSubstitution.SubstituteCustomModifiers(_originalDefinition.Type, _originalDefinition.CustomModifiers) End Get End Property Public Overrides ReadOnly Property OriginalDefinition As ParameterSymbol Get Return _originalDefinition End Get End Property Protected MustOverride ReadOnly Property TypeSubstitution As TypeSubstitution Public Overrides Function GetHashCode() As Integer Dim _hash As Integer = _originalDefinition.GetHashCode() Return Hash.Combine(ContainingSymbol, _hash) End Function Public Overrides Function Equals(obj As Object) As Boolean If Me Is obj Then Return True End If Dim other = TryCast(obj, SubstitutedParameterSymbol) If other Is Nothing Then Return False End If If Not _originalDefinition.Equals(other._originalDefinition) Then Return False End If If Not ContainingSymbol.Equals(other.ContainingSymbol) Then Return False End If Return True End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return _originalDefinition.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function ''' <summary> ''' Represents a method parameter that has undergone type substitution. ''' </summary> Friend Class SubstitutedMethodParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedMethodSymbol Public Sub New(container As SubstitutedMethodSymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution End Get End Property End Class ''' <summary> ''' Represents a property parameter that has undergone type substitution. ''' </summary> Private NotInheritable Class SubstitutedPropertyParameterSymbol Inherits SubstitutedParameterSymbol Private ReadOnly _container As SubstitutedPropertySymbol Public Sub New(container As SubstitutedPropertySymbol, originalDefinition As ParameterSymbol) MyBase.New(originalDefinition) _container = container End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Protected Overrides ReadOnly Property TypeSubstitution As TypeSubstitution Get Return _container.TypeSubstitution End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Syntax/Parsing/NameAttributeValueParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Compilers.CSharp.UnitTests { public class NameAttributeValueParsingTests : ParsingTests { public NameAttributeValueParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <param name=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlNameAttributeSyntax>().Single(); return attr.Identifier; } [Fact] public void Identifier() { UsingNode("A"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Keyword() { UsingNode("int"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Empty() { UsingNode(""); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Whitespace() { UsingNode(" "); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Qualified() { // Everything after the first identifier is skipped. UsingNode("A.B"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Generic() { // Everything after the first identifier is skipped. UsingNode("A{T}"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Punctuation() { // A missing identifier is inserted and everything is skipped. UsingNode("."); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Compilers.CSharp.UnitTests { public class NameAttributeValueParsingTests : ParsingTests { public NameAttributeValueParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { throw new NotSupportedException(); } protected override CSharpSyntaxNode ParseNode(string text, CSharpParseOptions options) { var commentText = string.Format(@"/// <param name=""{0}""/>", text); var trivia = SyntaxFactory.ParseLeadingTrivia(commentText).Single(); var structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure(); var attr = structure.DescendantNodes().OfType<XmlNameAttributeSyntax>().Single(); return attr.Identifier; } [Fact] public void Identifier() { UsingNode("A"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Keyword() { UsingNode("int"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Empty() { UsingNode(""); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Whitespace() { UsingNode(" "); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Qualified() { // Everything after the first identifier is skipped. UsingNode("A.B"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Generic() { // Everything after the first identifier is skipped. UsingNode("A{T}"); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } EOF(); } [Fact] public void Punctuation() { // A missing identifier is inserted and everything is skipped. UsingNode("."); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } EOF(); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/CodeStyle/Core/CodeFixes/xlf/CodeStyleFixesResources.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="../CodeStyleFixesResources.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="../CodeStyleFixesResources.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
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/EditorFeatures/Core/Implementation/Workspaces/TextUndoHistoryWorkspaceServiceFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(ITextUndoHistoryWorkspaceService), ServiceLayer.Default), Shared] internal class TextUndoHistoryWorkspaceServiceFactoryService : IWorkspaceServiceFactory { private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TextUndoHistoryWorkspaceServiceFactoryService(ITextUndoHistoryRegistry textUndoHistoryRegistry) => _textUndoHistoryRegistry = textUndoHistoryRegistry; public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new TextUndoHistoryWorkspaceService(_textUndoHistoryRegistry); private class TextUndoHistoryWorkspaceService : ITextUndoHistoryWorkspaceService { private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; public TextUndoHistoryWorkspaceService(ITextUndoHistoryRegistry textUndoHistoryRegistry) => _textUndoHistoryRegistry = textUndoHistoryRegistry; public bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory) => _textUndoHistoryRegistry.TryGetHistory(textBuffer, out undoHistory); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; namespace Microsoft.CodeAnalysis.Editor.Implementation.Workspaces { [ExportWorkspaceServiceFactory(typeof(ITextUndoHistoryWorkspaceService), ServiceLayer.Default), Shared] internal class TextUndoHistoryWorkspaceServiceFactoryService : IWorkspaceServiceFactory { private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TextUndoHistoryWorkspaceServiceFactoryService(ITextUndoHistoryRegistry textUndoHistoryRegistry) => _textUndoHistoryRegistry = textUndoHistoryRegistry; public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new TextUndoHistoryWorkspaceService(_textUndoHistoryRegistry); private class TextUndoHistoryWorkspaceService : ITextUndoHistoryWorkspaceService { private readonly ITextUndoHistoryRegistry _textUndoHistoryRegistry; public TextUndoHistoryWorkspaceService(ITextUndoHistoryRegistry textUndoHistoryRegistry) => _textUndoHistoryRegistry = textUndoHistoryRegistry; public bool TryGetTextUndoHistory(Workspace editorWorkspace, ITextBuffer textBuffer, out ITextUndoHistory undoHistory) => _textUndoHistoryRegistry.TryGetHistory(textBuffer, out undoHistory); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Errors/ErrorCode.cs
// Licensed to the .NET Foundation under one or more 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 { internal enum ErrorCode { Void = InternalErrorCode.Void, Unknown = InternalErrorCode.Unknown, #region diagnostics introduced in C# 4 and earlier //FTL_InternalError = 1, //FTL_FailedToLoadResource = 2, //FTL_NoMemory = 3, //ERR_WarningAsError = 4, //ERR_MissingOptionArg = 5, ERR_NoMetadataFile = 6, //FTL_ComPlusInit = 7, //FTL_MetadataImportFailure = 8, no longer used in Roslyn. FTL_MetadataCantOpenFile = 9, //ERR_FatalError = 10, //ERR_CantImportBase = 11, ERR_NoTypeDef = 12, //FTL_MetadataEmitFailure = 13, Roslyn does not catch stream writing exceptions. Those are propagated to the caller. //FTL_RequiredFileNotFound = 14, //ERR_ClassNameTooLong = 15, Deprecated in favor of ERR_MetadataNameTooLong. ERR_OutputWriteFailed = 16, ERR_MultipleEntryPoints = 17, //ERR_UnimplementedOp = 18, ERR_BadBinaryOps = 19, ERR_IntDivByZero = 20, ERR_BadIndexLHS = 21, ERR_BadIndexCount = 22, ERR_BadUnaryOp = 23, //ERR_NoStdLib = 25, not used in Roslyn ERR_ThisInStaticMeth = 26, ERR_ThisInBadContext = 27, WRN_InvalidMainSig = 28, ERR_NoImplicitConv = 29, // Requires SymbolDistinguisher. ERR_NoExplicitConv = 30, // Requires SymbolDistinguisher. ERR_ConstOutOfRange = 31, ERR_AmbigBinaryOps = 34, ERR_AmbigUnaryOp = 35, ERR_InAttrOnOutParam = 36, ERR_ValueCantBeNull = 37, //ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired "An object reference is required for the non-static..." ERR_NoExplicitBuiltinConv = 39, // Requires SymbolDistinguisher. //FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. FTL_DebugEmitFailure = 41, //FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info. //FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. ERR_BadVisReturnType = 50, ERR_BadVisParamType = 51, ERR_BadVisFieldType = 52, ERR_BadVisPropertyType = 53, ERR_BadVisIndexerReturn = 54, ERR_BadVisIndexerParam = 55, ERR_BadVisOpReturn = 56, ERR_BadVisOpParam = 57, ERR_BadVisDelegateReturn = 58, ERR_BadVisDelegateParam = 59, ERR_BadVisBaseClass = 60, ERR_BadVisBaseInterface = 61, ERR_EventNeedsBothAccessors = 65, ERR_EventNotDelegate = 66, WRN_UnreferencedEvent = 67, ERR_InterfaceEventInitializer = 68, //ERR_EventPropertyInInterface = 69, ERR_BadEventUsage = 70, ERR_ExplicitEventFieldImpl = 71, ERR_CantOverrideNonEvent = 72, ERR_AddRemoveMustHaveBody = 73, ERR_AbstractEventInitializer = 74, ERR_PossibleBadNegCast = 75, ERR_ReservedEnumerator = 76, ERR_AsMustHaveReferenceType = 77, WRN_LowercaseEllSuffix = 78, ERR_BadEventUsageNoField = 79, ERR_ConstraintOnlyAllowedOnGenericDecl = 80, ERR_TypeParamMustBeIdentifier = 81, ERR_MemberReserved = 82, ERR_DuplicateParamName = 100, ERR_DuplicateNameInNS = 101, ERR_DuplicateNameInClass = 102, ERR_NameNotInContext = 103, ERR_AmbigContext = 104, WRN_DuplicateUsing = 105, ERR_BadMemberFlag = 106, ERR_BadMemberProtection = 107, WRN_NewRequired = 108, WRN_NewNotRequired = 109, ERR_CircConstValue = 110, ERR_MemberAlreadyExists = 111, ERR_StaticNotVirtual = 112, ERR_OverrideNotNew = 113, WRN_NewOrOverrideExpected = 114, ERR_OverrideNotExpected = 115, ERR_NamespaceUnexpected = 116, ERR_NoSuchMember = 117, ERR_BadSKknown = 118, ERR_BadSKunknown = 119, ERR_ObjectRequired = 120, ERR_AmbigCall = 121, ERR_BadAccess = 122, ERR_MethDelegateMismatch = 123, ERR_RetObjectRequired = 126, ERR_RetNoObjectRequired = 127, ERR_LocalDuplicate = 128, ERR_AssgLvalueExpected = 131, ERR_StaticConstParam = 132, ERR_NotConstantExpression = 133, ERR_NotNullConstRefField = 134, // ERR_NameIllegallyOverrides = 135, // Not used in Roslyn anymore due to 'Single Meaning' relaxation changes ERR_LocalIllegallyOverrides = 136, ERR_BadUsingNamespace = 138, ERR_NoBreakOrCont = 139, ERR_DuplicateLabel = 140, ERR_NoConstructors = 143, ERR_NoNewAbstract = 144, ERR_ConstValueRequired = 145, ERR_CircularBase = 146, ERR_BadDelegateConstructor = 148, ERR_MethodNameExpected = 149, ERR_ConstantExpected = 150, // ERR_V6SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler. // However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future // we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used. ERR_V6SwitchGoverningTypeValueExpected = 151, ERR_DuplicateCaseLabel = 152, ERR_InvalidGotoCase = 153, ERR_PropertyLacksGet = 154, ERR_BadExceptionType = 155, ERR_BadEmptyThrow = 156, ERR_BadFinallyLeave = 157, ERR_LabelShadow = 158, ERR_LabelNotFound = 159, ERR_UnreachableCatch = 160, ERR_ReturnExpected = 161, WRN_UnreachableCode = 162, ERR_SwitchFallThrough = 163, WRN_UnreferencedLabel = 164, ERR_UseDefViolation = 165, //ERR_NoInvoke = 167, WRN_UnreferencedVar = 168, WRN_UnreferencedField = 169, ERR_UseDefViolationField = 170, ERR_UnassignedThis = 171, ERR_AmbigQM = 172, ERR_InvalidQM = 173, // Requires SymbolDistinguisher. ERR_NoBaseClass = 174, ERR_BaseIllegal = 175, ERR_ObjectProhibited = 176, ERR_ParamUnassigned = 177, ERR_InvalidArray = 178, ERR_ExternHasBody = 179, ERR_AbstractAndExtern = 180, ERR_BadAttributeParamType = 181, ERR_BadAttributeArgument = 182, WRN_IsAlwaysTrue = 183, WRN_IsAlwaysFalse = 184, ERR_LockNeedsReference = 185, ERR_NullNotValid = 186, ERR_UseDefViolationThis = 188, ERR_ArgsInvalid = 190, ERR_AssgReadonly = 191, ERR_RefReadonly = 192, ERR_PtrExpected = 193, ERR_PtrIndexSingle = 196, WRN_ByRefNonAgileField = 197, ERR_AssgReadonlyStatic = 198, ERR_RefReadonlyStatic = 199, ERR_AssgReadonlyProp = 200, ERR_IllegalStatement = 201, ERR_BadGetEnumerator = 202, ERR_TooManyLocals = 204, ERR_AbstractBaseCall = 205, ERR_RefProperty = 206, // WRN_OldWarning_UnsafeProp = 207, // This error code is unused. ERR_ManagedAddr = 208, ERR_BadFixedInitType = 209, ERR_FixedMustInit = 210, ERR_InvalidAddrOp = 211, ERR_FixedNeeded = 212, ERR_FixedNotNeeded = 213, ERR_UnsafeNeeded = 214, ERR_OpTFRetType = 215, ERR_OperatorNeedsMatch = 216, ERR_BadBoolOp = 217, ERR_MustHaveOpTF = 218, WRN_UnreferencedVarAssg = 219, ERR_CheckedOverflow = 220, ERR_ConstOutOfRangeChecked = 221, ERR_BadVarargs = 224, ERR_ParamsMustBeArray = 225, ERR_IllegalArglist = 226, ERR_IllegalUnsafe = 227, //ERR_NoAccessibleMember = 228, ERR_AmbigMember = 229, ERR_BadForeachDecl = 230, ERR_ParamsLast = 231, ERR_SizeofUnsafe = 233, ERR_DottedTypeNameNotFoundInNS = 234, ERR_FieldInitRefNonstatic = 236, ERR_SealedNonOverride = 238, ERR_CantOverrideSealed = 239, //ERR_NoDefaultArgs = 241, ERR_VoidError = 242, ERR_ConditionalOnOverride = 243, ERR_PointerInAsOrIs = 244, ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated ERR_SingleTypeNameNotFound = 246, ERR_NegativeStackAllocSize = 247, ERR_NegativeArraySize = 248, ERR_OverrideFinalizeDeprecated = 249, ERR_CallingBaseFinalizeDeprecated = 250, WRN_NegativeArrayIndex = 251, WRN_BadRefCompareLeft = 252, WRN_BadRefCompareRight = 253, ERR_BadCastInFixed = 254, ERR_StackallocInCatchFinally = 255, ERR_VarargsLast = 257, ERR_MissingPartial = 260, ERR_PartialTypeKindConflict = 261, ERR_PartialModifierConflict = 262, ERR_PartialMultipleBases = 263, ERR_PartialWrongTypeParams = 264, ERR_PartialWrongConstraints = 265, ERR_NoImplicitConvCast = 266, // Requires SymbolDistinguisher. ERR_PartialMisplaced = 267, ERR_ImportedCircularBase = 268, ERR_UseDefViolationOut = 269, ERR_ArraySizeInDeclaration = 270, ERR_InaccessibleGetter = 271, ERR_InaccessibleSetter = 272, ERR_InvalidPropertyAccessMod = 273, ERR_DuplicatePropertyAccessMods = 274, //ERR_PropertyAccessModInInterface = 275, ERR_AccessModMissingAccessor = 276, ERR_UnimplementedInterfaceAccessor = 277, WRN_PatternIsAmbiguous = 278, WRN_PatternNotPublicOrNotInstance = 279, WRN_PatternBadSignature = 280, ERR_FriendRefNotEqualToThis = 281, WRN_SequentialOnPartialClass = 282, ERR_BadConstType = 283, ERR_NoNewTyvar = 304, ERR_BadArity = 305, ERR_BadTypeArgument = 306, ERR_TypeArgsNotAllowed = 307, ERR_HasNoTypeVars = 308, ERR_NewConstraintNotSatisfied = 310, ERR_GenericConstraintNotSatisfiedRefType = 311, // Requires SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedNullableEnum = 312, // Uses (but doesn't require) SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedNullableInterface = 313, // Uses (but doesn't require) SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedTyVar = 314, // Requires SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedValType = 315, // Requires SymbolDistinguisher. ERR_DuplicateGeneratedName = 316, // unused 317-399 ERR_GlobalSingleTypeNameNotFound = 400, ERR_NewBoundMustBeLast = 401, WRN_MainCantBeGeneric = 402, ERR_TypeVarCantBeNull = 403, ERR_AttributeCantBeGeneric = 404, ERR_DuplicateBound = 405, ERR_ClassBoundNotFirst = 406, ERR_BadRetType = 407, ERR_DuplicateConstraintClause = 409, //ERR_WrongSignature = 410, unused in Roslyn ERR_CantInferMethTypeArgs = 411, ERR_LocalSameNameAsTypeParam = 412, ERR_AsWithTypeVar = 413, WRN_UnreferencedFieldAssg = 414, ERR_BadIndexerNameAttr = 415, ERR_AttrArgWithTypeVars = 416, ERR_NewTyvarWithArgs = 417, ERR_AbstractSealedStatic = 418, WRN_AmbiguousXMLReference = 419, WRN_VolatileByRef = 420, // WRN_IncrSwitchObsolete = 422, // This error code is unused. ERR_ComImportWithImpl = 423, ERR_ComImportWithBase = 424, ERR_ImplBadConstraints = 425, ERR_DottedTypeNameNotFoundInAgg = 426, ERR_MethGrpToNonDel = 428, // WRN_UnreachableExpr = 429, // This error code is unused. ERR_BadExternAlias = 430, ERR_ColColWithTypeAlias = 431, ERR_AliasNotFound = 432, ERR_SameFullNameAggAgg = 433, ERR_SameFullNameNsAgg = 434, WRN_SameFullNameThisNsAgg = 435, WRN_SameFullNameThisAggAgg = 436, WRN_SameFullNameThisAggNs = 437, ERR_SameFullNameThisAggThisNs = 438, ERR_ExternAfterElements = 439, WRN_GlobalAliasDefn = 440, ERR_SealedStaticClass = 441, ERR_PrivateAbstractAccessor = 442, ERR_ValueExpected = 443, // WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused. ERR_UnboxNotLValue = 445, ERR_AnonMethGrpInForEach = 446, //ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error. ERR_BadIncDecRetType = 448, ERR_TypeConstraintsMustBeUniqueAndFirst = 449, ERR_RefValBoundWithClass = 450, ERR_NewBoundWithVal = 451, ERR_RefConstraintNotSatisfied = 452, ERR_ValConstraintNotSatisfied = 453, ERR_CircularConstraint = 454, ERR_BaseConstraintConflict = 455, ERR_ConWithValCon = 456, ERR_AmbigUDConv = 457, WRN_AlwaysNull = 458, // ERR_AddrOnReadOnlyLocal = 459, // no longer an error ERR_OverrideWithConstraints = 460, ERR_AmbigOverride = 462, ERR_DecConstError = 463, WRN_CmpAlwaysFalse = 464, WRN_FinalizeMethod = 465, ERR_ExplicitImplParams = 466, // WRN_AmbigLookupMeth = 467, //no longer issued in Roslyn //ERR_SameFullNameThisAggThisAgg = 468, no longer used in Roslyn WRN_GotoCaseShouldConvert = 469, ERR_MethodImplementingAccessor = 470, //ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn WRN_NubExprIsConstBool = 472, WRN_ExplicitImplCollision = 473, // unused 474-499 ERR_AbstractHasBody = 500, ERR_ConcreteMissingBody = 501, ERR_AbstractAndSealed = 502, ERR_AbstractNotVirtual = 503, ERR_StaticConstant = 504, ERR_CantOverrideNonFunction = 505, ERR_CantOverrideNonVirtual = 506, ERR_CantChangeAccessOnOverride = 507, ERR_CantChangeReturnTypeOnOverride = 508, ERR_CantDeriveFromSealedType = 509, ERR_AbstractInConcreteClass = 513, ERR_StaticConstructorWithExplicitConstructorCall = 514, ERR_StaticConstructorWithAccessModifiers = 515, ERR_RecursiveConstructorCall = 516, ERR_ObjectCallingBaseConstructor = 517, ERR_PredefinedTypeNotFound = 518, //ERR_PredefinedTypeBadType = 520, ERR_StructWithBaseConstructorCall = 522, ERR_StructLayoutCycle = 523, //ERR_InterfacesCannotContainTypes = 524, ERR_InterfacesCantContainFields = 525, ERR_InterfacesCantContainConstructors = 526, ERR_NonInterfaceInInterfaceList = 527, ERR_DuplicateInterfaceInBaseList = 528, ERR_CycleInInterfaceInheritance = 529, //ERR_InterfaceMemberHasBody = 531, ERR_HidingAbstractMethod = 533, ERR_UnimplementedAbstractMethod = 534, ERR_UnimplementedInterfaceMember = 535, ERR_ObjectCantHaveBases = 537, ERR_ExplicitInterfaceImplementationNotInterface = 538, ERR_InterfaceMemberNotFound = 539, ERR_ClassDoesntImplementInterface = 540, ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541, ERR_MemberNameSameAsType = 542, ERR_EnumeratorOverflow = 543, ERR_CantOverrideNonProperty = 544, ERR_NoGetToOverride = 545, ERR_NoSetToOverride = 546, ERR_PropertyCantHaveVoidType = 547, ERR_PropertyWithNoAccessors = 548, ERR_NewVirtualInSealed = 549, ERR_ExplicitPropertyAddingAccessor = 550, ERR_ExplicitPropertyMissingAccessor = 551, ERR_ConversionWithInterface = 552, ERR_ConversionWithBase = 553, ERR_ConversionWithDerived = 554, ERR_IdentityConversion = 555, ERR_ConversionNotInvolvingContainedType = 556, ERR_DuplicateConversionInClass = 557, ERR_OperatorsMustBeStatic = 558, ERR_BadIncDecSignature = 559, ERR_BadUnaryOperatorSignature = 562, ERR_BadBinaryOperatorSignature = 563, ERR_BadShiftOperatorSignature = 564, ERR_InterfacesCantContainConversionOrEqualityOperators = 567, //ERR_StructsCantContainDefaultConstructor = 568, ERR_CantOverrideBogusMethod = 569, ERR_BindToBogus = 570, ERR_CantCallSpecialMethod = 571, ERR_BadTypeReference = 572, //ERR_FieldInitializerInStruct = 573, ERR_BadDestructorName = 574, ERR_OnlyClassesCanContainDestructors = 575, ERR_ConflictAliasAndMember = 576, ERR_ConditionalOnSpecialMethod = 577, ERR_ConditionalMustReturnVoid = 578, ERR_DuplicateAttribute = 579, ERR_ConditionalOnInterfaceMethod = 582, //ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused //ERR_ICE_Symbol = 584, //ERR_ICE_Node = 585, //ERR_ICE_File = 586, //ERR_ICE_Stage = 587, //ERR_ICE_Lexer = 588, //ERR_ICE_Parser = 589, ERR_OperatorCantReturnVoid = 590, ERR_InvalidAttributeArgument = 591, ERR_AttributeOnBadSymbolType = 592, ERR_FloatOverflow = 594, ERR_InvalidReal = 595, ERR_ComImportWithoutUuidAttribute = 596, ERR_InvalidNamedArgument = 599, ERR_DllImportOnInvalidMethod = 601, // WRN_FeatureDeprecated = 602, // This error code is unused. // ERR_NameAttributeOnOverride = 609, // removed in Roslyn ERR_FieldCantBeRefAny = 610, ERR_ArrayElementCantBeRefAny = 611, WRN_DeprecatedSymbol = 612, ERR_NotAnAttributeClass = 616, ERR_BadNamedAttributeArgument = 617, WRN_DeprecatedSymbolStr = 618, ERR_DeprecatedSymbolStr = 619, ERR_IndexerCantHaveVoidType = 620, ERR_VirtualPrivate = 621, ERR_ArrayInitToNonArrayType = 622, ERR_ArrayInitInBadPlace = 623, ERR_MissingStructOffset = 625, WRN_ExternMethodNoImplementation = 626, WRN_ProtectedInSealed = 628, ERR_InterfaceImplementedByConditional = 629, ERR_InterfaceImplementedImplicitlyByVariadic = 630, ERR_IllegalRefParam = 631, ERR_BadArgumentToAttribute = 633, //ERR_MissingComTypeOrMarshaller = 635, ERR_StructOffsetOnBadStruct = 636, ERR_StructOffsetOnBadField = 637, ERR_AttributeUsageOnNonAttributeClass = 641, WRN_PossibleMistakenNullStatement = 642, ERR_DuplicateNamedAttributeArgument = 643, ERR_DeriveFromEnumOrValueType = 644, //ERR_IdentifierTooLong = 645, //not used in Roslyn. See ERR_MetadataNameTooLong ERR_DefaultMemberOnIndexedType = 646, //ERR_CustomAttributeError = 647, ERR_BogusType = 648, WRN_UnassignedInternalField = 649, ERR_CStyleArray = 650, WRN_VacuousIntegralComp = 652, ERR_AbstractAttributeClass = 653, ERR_BadNamedAttributeArgumentType = 655, ERR_MissingPredefinedMember = 656, WRN_AttributeLocationOnBadDeclaration = 657, WRN_InvalidAttributeLocation = 658, WRN_EqualsWithoutGetHashCode = 659, WRN_EqualityOpWithoutEquals = 660, WRN_EqualityOpWithoutGetHashCode = 661, ERR_OutAttrOnRefParam = 662, ERR_OverloadRefKind = 663, ERR_LiteralDoubleCast = 664, WRN_IncorrectBooleanAssg = 665, ERR_ProtectedInStruct = 666, //ERR_FeatureDeprecated = 667, ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler ERR_ComImportWithUserCtor = 669, ERR_FieldCantHaveVoidType = 670, WRN_NonObsoleteOverridingObsolete = 672, ERR_SystemVoid = 673, ERR_ExplicitParamArray = 674, WRN_BitwiseOrSignExtend = 675, ERR_VolatileStruct = 677, ERR_VolatileAndReadonly = 678, // WRN_OldWarning_ProtectedInternal = 679, // This error code is unused. // WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused. ERR_AbstractField = 681, ERR_BogusExplicitImpl = 682, ERR_ExplicitMethodImplAccessor = 683, WRN_CoClassWithoutComImport = 684, ERR_ConditionalWithOutParam = 685, ERR_AccessorImplementingMethod = 686, ERR_AliasQualAsExpression = 687, ERR_DerivingFromATyVar = 689, //FTL_MalformedMetadata = 690, ERR_DuplicateTypeParameter = 692, WRN_TypeParameterSameAsOuterTypeParameter = 693, ERR_TypeVariableSameAsParent = 694, ERR_UnifyingInterfaceInstantiations = 695, ERR_GenericDerivingFromAttribute = 698, ERR_TyVarNotFoundInConstraint = 699, ERR_BadBoundType = 701, ERR_SpecialTypeAsBound = 702, ERR_BadVisBound = 703, ERR_LookupInTypeVariable = 704, ERR_BadConstraintType = 706, ERR_InstanceMemberInStaticClass = 708, ERR_StaticBaseClass = 709, ERR_ConstructorInStaticClass = 710, ERR_DestructorInStaticClass = 711, ERR_InstantiatingStaticClass = 712, ERR_StaticDerivedFromNonObject = 713, ERR_StaticClassInterfaceImpl = 714, ERR_OperatorInStaticClass = 715, ERR_ConvertToStaticClass = 716, ERR_ConstraintIsStaticClass = 717, ERR_GenericArgIsStaticClass = 718, ERR_ArrayOfStaticClass = 719, ERR_IndexerInStaticClass = 720, ERR_ParameterIsStaticClass = 721, ERR_ReturnTypeIsStaticClass = 722, ERR_VarDeclIsStaticClass = 723, ERR_BadEmptyThrowInFinally = 724, //ERR_InvalidDecl = 725, ERR_InvalidSpecifier = 726, //ERR_InvalidSpecifierUnk = 727, WRN_AssignmentToLockOrDispose = 728, ERR_ForwardedTypeInThisAssembly = 729, ERR_ForwardedTypeIsNested = 730, ERR_CycleInTypeForwarder = 731, //ERR_FwdedGeneric = 733, ERR_AssemblyNameOnNonModule = 734, ERR_InvalidFwdType = 735, ERR_CloseUnimplementedInterfaceMemberStatic = 736, ERR_CloseUnimplementedInterfaceMemberNotPublic = 737, ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738, ERR_DuplicateTypeForwarder = 739, ERR_ExpectedSelectOrGroup = 742, ERR_ExpectedContextualKeywordOn = 743, ERR_ExpectedContextualKeywordEquals = 744, ERR_ExpectedContextualKeywordBy = 745, ERR_InvalidAnonymousTypeMemberDeclarator = 746, ERR_InvalidInitializerElementInitializer = 747, ERR_InconsistentLambdaParameterUsage = 748, ERR_PartialMethodInvalidModifier = 750, ERR_PartialMethodOnlyInPartialClass = 751, // ERR_PartialMethodCannotHaveOutParameters = 752, Removed as part of 'extended partial methods' feature // ERR_PartialMethodOnlyMethods = 753, Removed as it is subsumed by ERR_PartialMisplaced ERR_PartialMethodNotExplicit = 754, ERR_PartialMethodExtensionDifference = 755, ERR_PartialMethodOnlyOneLatent = 756, ERR_PartialMethodOnlyOneActual = 757, ERR_PartialMethodParamsDifference = 758, ERR_PartialMethodMustHaveLatent = 759, ERR_PartialMethodInconsistentConstraints = 761, ERR_PartialMethodToDelegate = 762, ERR_PartialMethodStaticDifference = 763, ERR_PartialMethodUnsafeDifference = 764, ERR_PartialMethodInExpressionTree = 765, // ERR_PartialMethodMustReturnVoid = 766, Removed as part of 'extended partial methods' feature ERR_ExplicitImplCollisionOnRefOut = 767, ERR_IndirectRecursiveConstructorCall = 768, // unused 769-799 //ERR_NoEmptyArrayRanges = 800, //ERR_IntegerSpecifierOnOneDimArrays = 801, //ERR_IntegerSpecifierMustBePositive = 802, //ERR_ArrayRangeDimensionsMustMatch = 803, //ERR_ArrayRangeDimensionsWrong = 804, //ERR_IntegerSpecifierValidOnlyOnArrays = 805, //ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806, //ERR_UseAdditionalSquareBrackets = 807, //ERR_DotDotNotAssociative = 808, WRN_ObsoleteOverridingNonObsolete = 809, WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer ERR_ImplicitlyTypedLocalCannotBeFixed = 821, ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst WRN_ExternCtorNoImplementation = 824, ERR_TypeVarNotFound = 825, ERR_ImplicitlyTypedArrayNoBestType = 826, ERR_AnonymousTypePropertyAssignedBadValue = 828, ERR_ExpressionTreeContainsBaseAccess = 831, ERR_ExpressionTreeContainsAssignment = 832, ERR_AnonymousTypeDuplicatePropertyName = 833, ERR_StatementLambdaToExpressionTree = 834, ERR_ExpressionTreeMustHaveDelegate = 835, ERR_AnonymousTypeNotAvailable = 836, ERR_LambdaInIsAs = 837, ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838, ERR_MissingArgument = 839, //ERR_AutoPropertiesMustHaveBothAccessors = 840, ERR_VariableUsedBeforeDeclaration = 841, //ERR_ExplicitLayoutAndAutoImplementedProperty = 842, ERR_UnassignedThisAutoProperty = 843, ERR_VariableUsedBeforeDeclarationAndHidesField = 844, ERR_ExpressionTreeContainsBadCoalesce = 845, ERR_ArrayInitializerExpected = 846, ERR_ArrayInitializerIncorrectLength = 847, // ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind ERR_ExpressionTreeContainsNamedArgument = 853, ERR_ExpressionTreeContainsOptionalArgument = 854, ERR_ExpressionTreeContainsIndexedProperty = 855, ERR_IndexedPropertyRequiresParams = 856, ERR_IndexedPropertyMustHaveAllOptionalParams = 857, //ERR_FusionConfigFileNameTooLong = 858, unused in Roslyn. We give ERR_CantReadConfigFile now. // unused 859-1000 ERR_IdentifierExpected = 1001, ERR_SemicolonExpected = 1002, ERR_SyntaxError = 1003, ERR_DuplicateModifier = 1004, ERR_DuplicateAccessor = 1007, ERR_IntegralTypeExpected = 1008, ERR_IllegalEscape = 1009, ERR_NewlineInConst = 1010, ERR_EmptyCharConst = 1011, ERR_TooManyCharsInConst = 1012, ERR_InvalidNumber = 1013, ERR_GetOrSetExpected = 1014, ERR_ClassTypeExpected = 1015, ERR_NamedArgumentExpected = 1016, ERR_TooManyCatches = 1017, ERR_ThisOrBaseExpected = 1018, ERR_OvlUnaryOperatorExpected = 1019, ERR_OvlBinaryOperatorExpected = 1020, ERR_IntOverflow = 1021, ERR_EOFExpected = 1022, ERR_BadEmbeddedStmt = 1023, ERR_PPDirectiveExpected = 1024, ERR_EndOfPPLineExpected = 1025, ERR_CloseParenExpected = 1026, ERR_EndifDirectiveExpected = 1027, ERR_UnexpectedDirective = 1028, ERR_ErrorDirective = 1029, WRN_WarningDirective = 1030, ERR_TypeExpected = 1031, ERR_PPDefFollowsToken = 1032, //ERR_TooManyLines = 1033, unused in Roslyn. //ERR_LineTooLong = 1034, unused in Roslyn. ERR_OpenEndedComment = 1035, ERR_OvlOperatorExpected = 1037, ERR_EndRegionDirectiveExpected = 1038, ERR_UnterminatedStringLit = 1039, ERR_BadDirectivePlacement = 1040, ERR_IdentifierExpectedKW = 1041, ERR_SemiOrLBraceExpected = 1043, ERR_MultiTypeInDeclaration = 1044, ERR_AddOrRemoveExpected = 1055, ERR_UnexpectedCharacter = 1056, ERR_ProtectedInStatic = 1057, WRN_UnreachableGeneralCatch = 1058, ERR_IncrementLvalueExpected = 1059, // WRN_UninitializedField = 1060, // unused in Roslyn. ERR_NoSuchMemberOrExtension = 1061, WRN_DeprecatedCollectionInitAddStr = 1062, ERR_DeprecatedCollectionInitAddStr = 1063, WRN_DeprecatedCollectionInitAdd = 1064, ERR_DefaultValueNotAllowed = 1065, WRN_DefaultValueForUnconsumedLocation = 1066, ERR_PartialWrongTypeParamsVariance = 1067, ERR_GlobalSingleTypeNameNotFoundFwd = 1068, ERR_DottedTypeNameNotFoundInNSFwd = 1069, ERR_SingleTypeNameNotFoundFwd = 1070, //ERR_NoSuchMemberOnNoPIAType = 1071, //EE WRN_IdentifierOrNumericLiteralExpected = 1072, ERR_UnexpectedToken = 1073, // unused 1074-1098 // ERR_EOLExpected = 1099, // EE // ERR_NotSupportedinEE = 1100, // EE ERR_BadThisParam = 1100, // ERR_BadRefWithThis = 1101, replaced by ERR_BadParameterModifiers // ERR_BadOutWithThis = 1102, replaced by ERR_BadParameterModifiers ERR_BadTypeforThis = 1103, ERR_BadParamModThis = 1104, ERR_BadExtensionMeth = 1105, ERR_BadExtensionAgg = 1106, ERR_DupParamMod = 1107, // ERR_MultiParamMod = 1108, replaced by ERR_BadParameterModifiers ERR_ExtensionMethodsDecl = 1109, ERR_ExtensionAttrNotFound = 1110, //ERR_ExtensionTypeParam = 1111, ERR_ExplicitExtension = 1112, ERR_ValueTypeExtDelegate = 1113, // unused 1114-1199 // Below five error codes are unused. // WRN_FeatureDeprecated2 = 1200, // WRN_FeatureDeprecated3 = 1201, // WRN_FeatureDeprecated4 = 1202, // WRN_FeatureDeprecated5 = 1203, // WRN_OldWarning_FeatureDefaultDeprecated = 1204, // unused 1205-1500 ERR_BadArgCount = 1501, //ERR_BadArgTypes = 1502, ERR_BadArgType = 1503, ERR_NoSourceFile = 1504, ERR_CantRefResource = 1507, ERR_ResourceNotUnique = 1508, ERR_ImportNonAssembly = 1509, ERR_RefLvalueExpected = 1510, ERR_BaseInStaticMeth = 1511, ERR_BaseInBadContext = 1512, ERR_RbraceExpected = 1513, ERR_LbraceExpected = 1514, ERR_InExpected = 1515, ERR_InvalidPreprocExpr = 1517, //ERR_BadTokenInType = 1518, unused in Roslyn ERR_InvalidMemberDecl = 1519, ERR_MemberNeedsType = 1520, ERR_BadBaseType = 1521, WRN_EmptySwitch = 1522, ERR_ExpectedEndTry = 1524, ERR_InvalidExprTerm = 1525, ERR_BadNewExpr = 1526, ERR_NoNamespacePrivate = 1527, ERR_BadVarDecl = 1528, ERR_UsingAfterElements = 1529, //ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this. //ERR_DontUseInvoke = 1533, ERR_BadBinOpArgs = 1534, ERR_BadUnOpArgs = 1535, ERR_NoVoidParameter = 1536, ERR_DuplicateAlias = 1537, ERR_BadProtectedAccess = 1540, //ERR_CantIncludeDirectory = 1541, ERR_AddModuleAssembly = 1542, ERR_BindToBogusProp2 = 1545, ERR_BindToBogusProp1 = 1546, ERR_NoVoidHere = 1547, //ERR_CryptoFailed = 1548, //ERR_CryptoNotFound = 1549, ERR_IndexerNeedsParam = 1551, ERR_BadArraySyntax = 1552, ERR_BadOperatorSyntax = 1553, //ERR_BadOperatorSyntax2 = 1554, Not used in Roslyn. ERR_MainClassNotFound = 1555, ERR_MainClassNotClass = 1556, //ERR_MainClassWrongFile = 1557, Not used in Roslyn. This was used only when compiling and producing two outputs. ERR_NoMainInClass = 1558, //ERR_MainClassIsImport = 1559, Not used in Roslyn. Scenario occurs so infrequently that it is not worth re-implementing. //ERR_FileNameTooLong = 1560, //ERR_OutputFileNameTooLong = 1561, Not used in Roslyn. We report a more generic error that doesn't mention "output file" but is fine. ERR_OutputNeedsName = 1562, //ERR_OutputNeedsInput = 1563, ERR_CantHaveWin32ResAndManifest = 1564, ERR_CantHaveWin32ResAndIcon = 1565, ERR_CantReadResource = 1566, //ERR_AutoResGen = 1567, ERR_DocFileGen = 1569, WRN_XMLParseError = 1570, WRN_DuplicateParamTag = 1571, WRN_UnmatchedParamTag = 1572, WRN_MissingParamTag = 1573, WRN_BadXMLRef = 1574, ERR_BadStackAllocExpr = 1575, ERR_InvalidLineNumber = 1576, //ERR_ALinkFailed = 1577, No alink usage in Roslyn ERR_MissingPPFile = 1578, ERR_ForEachMissingMember = 1579, WRN_BadXMLRefParamType = 1580, WRN_BadXMLRefReturnType = 1581, ERR_BadWin32Res = 1583, WRN_BadXMLRefSyntax = 1584, ERR_BadModifierLocation = 1585, ERR_MissingArraySize = 1586, WRN_UnprocessedXMLComment = 1587, //ERR_CantGetCORSystemDir = 1588, WRN_FailedInclude = 1589, WRN_InvalidInclude = 1590, WRN_MissingXMLComment = 1591, WRN_XMLParseIncludeError = 1592, ERR_BadDelArgCount = 1593, //ERR_BadDelArgTypes = 1594, // WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused. // WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused. ERR_UnexpectedSemicolon = 1597, // WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time). ERR_MethodReturnCantBeRefAny = 1599, ERR_CompileCancelled = 1600, ERR_MethodArgCantBeRefAny = 1601, ERR_AssgReadonlyLocal = 1604, ERR_RefReadonlyLocal = 1605, //ERR_ALinkCloseFailed = 1606, WRN_ALinkWarn = 1607, ERR_CantUseRequiredAttribute = 1608, ERR_NoModifiersOnAccessor = 1609, // WRN_DeleteAutoResFailed = 1610, // Unused. ERR_ParamsCantBeWithModifier = 1611, ERR_ReturnNotLValue = 1612, ERR_MissingCoClass = 1613, ERR_AmbiguousAttribute = 1614, ERR_BadArgExtraRef = 1615, WRN_CmdOptionConflictsSource = 1616, ERR_BadCompatMode = 1617, ERR_DelegateOnConditional = 1618, ERR_CantMakeTempFile = 1619, //changed to now accept only one argument ERR_BadArgRef = 1620, ERR_YieldInAnonMeth = 1621, ERR_ReturnInIterator = 1622, ERR_BadIteratorArgType = 1623, ERR_BadIteratorReturn = 1624, ERR_BadYieldInFinally = 1625, ERR_BadYieldInTryOfCatch = 1626, ERR_EmptyYield = 1627, ERR_AnonDelegateCantUse = 1628, ERR_IllegalInnerUnsafe = 1629, //ERR_BadWatsonMode = 1630, ERR_BadYieldInCatch = 1631, ERR_BadDelegateLeave = 1632, WRN_IllegalPragma = 1633, WRN_IllegalPPWarning = 1634, WRN_BadRestoreNumber = 1635, ERR_VarargsIterator = 1636, ERR_UnsafeIteratorArgType = 1637, //ERR_ReservedIdentifier = 1638, ERR_BadCoClassSig = 1639, ERR_MultipleIEnumOfT = 1640, ERR_FixedDimsRequired = 1641, ERR_FixedNotInStruct = 1642, ERR_AnonymousReturnExpected = 1643, //ERR_NonECMAFeature = 1644, WRN_NonECMAFeature = 1645, ERR_ExpectedVerbatimLiteral = 1646, //FTL_StackOverflow = 1647, ERR_AssgReadonly2 = 1648, ERR_RefReadonly2 = 1649, ERR_AssgReadonlyStatic2 = 1650, ERR_RefReadonlyStatic2 = 1651, ERR_AssgReadonlyLocal2Cause = 1654, ERR_RefReadonlyLocal2Cause = 1655, ERR_AssgReadonlyLocalCause = 1656, ERR_RefReadonlyLocalCause = 1657, WRN_ErrorOverride = 1658, // WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused. ERR_AnonMethToNonDel = 1660, ERR_CantConvAnonMethParams = 1661, ERR_CantConvAnonMethReturns = 1662, ERR_IllegalFixedType = 1663, ERR_FixedOverflow = 1664, ERR_InvalidFixedArraySize = 1665, ERR_FixedBufferNotFixed = 1666, ERR_AttributeNotOnAccessor = 1667, WRN_InvalidSearchPathDir = 1668, ERR_IllegalVarArgs = 1669, ERR_IllegalParams = 1670, ERR_BadModifiersOnNamespace = 1671, ERR_BadPlatformType = 1672, ERR_ThisStructNotInAnonMeth = 1673, ERR_NoConvToIDisp = 1674, // ERR_InvalidGenericEnum = 1675, replaced with 7002 ERR_BadParamRef = 1676, ERR_BadParamExtraRef = 1677, ERR_BadParamType = 1678, // Requires SymbolDistinguisher. ERR_BadExternIdentifier = 1679, ERR_AliasMissingFile = 1680, ERR_GlobalExternAlias = 1681, // WRN_MissingTypeNested = 1682, // unused in Roslyn. // In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively. // WRN_MissingTypeInSource = 1683, // WRN_MissingTypeInAssembly = 1684, WRN_MultiplePredefTypes = 1685, ERR_LocalCantBeFixedAndHoisted = 1686, WRN_TooManyLinesForDebugger = 1687, ERR_CantConvAnonMethNoParams = 1688, ERR_ConditionalOnNonAttributeClass = 1689, WRN_CallOnNonAgileField = 1690, // WRN_BadWarningNumber = 1691, // we no longer generate this warning for an unrecognized warning ID specified as an argument to /nowarn or /warnaserror. WRN_InvalidNumber = 1692, // WRN_FileNameTooLong = 1694, //unused. WRN_IllegalPPChecksum = 1695, WRN_EndOfPPLineExpected = 1696, WRN_ConflictingChecksum = 1697, // WRN_AssumedMatchThis = 1698, // This error code is unused. // WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused. WRN_InvalidAssemblyName = 1700, WRN_UnifyReferenceMajMin = 1701, WRN_UnifyReferenceBldRev = 1702, ERR_DuplicateImport = 1703, ERR_DuplicateImportSimple = 1704, ERR_AssemblyMatchBadVersion = 1705, //ERR_AnonMethNotAllowed = 1706, Unused in Roslyn. Previously given when a lambda was supplied as an attribute argument. // WRN_DelegateNewMethBind = 1707, // This error code is unused. ERR_FixedNeedsLvalue = 1708, // WRN_EmptyFileName = 1709, // This error code is unused. WRN_DuplicateTypeParamTag = 1710, WRN_UnmatchedTypeParamTag = 1711, WRN_MissingTypeParamTag = 1712, //FTL_TypeNameBuilderError = 1713, //ERR_ImportBadBase = 1714, // This error code is unused and replaced with ERR_NoTypeDef ERR_CantChangeTypeOnOverride = 1715, ERR_DoNotUseFixedBufferAttr = 1716, WRN_AssignmentToSelf = 1717, WRN_ComparisonToSelf = 1718, ERR_CantOpenWin32Res = 1719, WRN_DotOnDefault = 1720, ERR_NoMultipleInheritance = 1721, ERR_BaseClassMustBeFirst = 1722, WRN_BadXMLRefTypeVar = 1723, //ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn. ERR_FriendAssemblyBadArgs = 1725, ERR_FriendAssemblySNReq = 1726, //ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings. ERR_DelegateOnNullable = 1728, ERR_BadCtorArgCount = 1729, ERR_GlobalAttributesNotFirst = 1730, //ERR_CantConvAnonMethReturnsNoDelegate = 1731, Not used in Roslyn. When there is no delegate, we reuse the message that contains a substitution string for the delegate type. //ERR_ParameterExpected = 1732, Not used in Roslyn. ERR_ExpressionExpected = 1733, WRN_UnmatchedParamRefTag = 1734, WRN_UnmatchedTypeParamRefTag = 1735, ERR_DefaultValueMustBeConstant = 1736, ERR_DefaultValueBeforeRequiredValue = 1737, ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738, ERR_BadNamedArgument = 1739, ERR_DuplicateNamedArgument = 1740, ERR_RefOutDefaultValue = 1741, ERR_NamedArgumentForArray = 1742, ERR_DefaultValueForExtensionParameter = 1743, ERR_NamedArgumentUsedInPositional = 1744, ERR_DefaultValueUsedWithAttributes = 1745, ERR_BadNamedArgumentForDelegateInvoke = 1746, ERR_NoPIAAssemblyMissingAttribute = 1747, ERR_NoCanonicalView = 1748, //ERR_TypeNotFoundForNoPIA = 1749, ERR_NoConversionForDefaultParam = 1750, ERR_DefaultValueForParamsParameter = 1751, ERR_NewCoClassOnLink = 1752, ERR_NoPIANestedType = 1754, //ERR_InvalidTypeIdentifierConstructor = 1755, ERR_InteropTypeMissingAttribute = 1756, ERR_InteropStructContainsMethods = 1757, ERR_InteropTypesWithSameNameAndGuid = 1758, ERR_NoPIAAssemblyMissingAttributes = 1759, ERR_AssemblySpecifiedForLinkAndRef = 1760, ERR_LocalTypeNameClash = 1761, WRN_ReferencedAssemblyReferencesLinkedPIA = 1762, ERR_NotNullRefDefaultParameter = 1763, ERR_FixedLocalInLambda = 1764, // WRN_TypeNotFoundForNoPIAWarning = 1765, // This error code is unused. ERR_MissingMethodOnSourceInterface = 1766, ERR_MissingSourceInterface = 1767, ERR_GenericsUsedInNoPIAType = 1768, ERR_GenericsUsedAcrossAssemblies = 1769, ERR_NoConversionForNubDefaultParam = 1770, //ERR_MemberWithGenericsUsedAcrossAssemblies = 1771, //ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772, ERR_InvalidSubsystemVersion = 1773, ERR_InteropMethodWithBody = 1774, // unused 1775-1899 ERR_BadWarningLevel = 1900, ERR_BadDebugType = 1902, //ERR_UnknownTestSwitch = 1903, ERR_BadResourceVis = 1906, ERR_DefaultValueTypeMustMatch = 1908, //ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn. ERR_DefaultValueBadValueType = 1910, ERR_MemberAlreadyInitialized = 1912, ERR_MemberCannotBeInitialized = 1913, ERR_StaticMemberInObjectInitializer = 1914, ERR_ReadonlyValueTypeInObjectInitializer = 1917, ERR_ValueTypePropertyInObjectInitializer = 1918, ERR_UnsafeTypeInObjectCreation = 1919, ERR_EmptyElementInitializer = 1920, ERR_InitializerAddHasWrongSignature = 1921, ERR_CollectionInitRequiresIEnumerable = 1922, //ERR_InvalidCollectionInitializerType = 1925, unused in Roslyn. Occurs so infrequently in real usage that it is not worth reimplementing. ERR_CantOpenWin32Manifest = 1926, WRN_CantHaveManifestForModule = 1927, //ERR_BadExtensionArgTypes = 1928, unused in Roslyn (replaced by ERR_BadInstanceArgType) ERR_BadInstanceArgType = 1929, ERR_QueryDuplicateRangeVariable = 1930, ERR_QueryRangeVariableOverrides = 1931, ERR_QueryRangeVariableAssignedBadValue = 1932, //ERR_QueryNotAllowed = 1933, unused in Roslyn. This specific message is not necessary for correctness and adds little. ERR_QueryNoProviderCastable = 1934, ERR_QueryNoProviderStandard = 1935, ERR_QueryNoProvider = 1936, ERR_QueryOuterKey = 1937, ERR_QueryInnerKey = 1938, ERR_QueryOutRefRangeVariable = 1939, ERR_QueryMultipleProviders = 1940, ERR_QueryTypeInferenceFailedMulti = 1941, ERR_QueryTypeInferenceFailed = 1942, ERR_QueryTypeInferenceFailedSelectMany = 1943, ERR_ExpressionTreeContainsPointerOp = 1944, ERR_ExpressionTreeContainsAnonymousMethod = 1945, ERR_AnonymousMethodToExpressionTree = 1946, ERR_QueryRangeVariableReadOnly = 1947, ERR_QueryRangeVariableSameAsTypeParam = 1948, ERR_TypeVarNotFoundRangeVariable = 1949, ERR_BadArgTypesForCollectionAdd = 1950, ERR_ByRefParameterInExpressionTree = 1951, ERR_VarArgsInExpressionTree = 1952, // ERR_MemGroupInExpressionTree = 1953, unused in Roslyn (replaced by ERR_LambdaInIsAs) ERR_InitializerAddHasParamModifiers = 1954, ERR_NonInvocableMemberCalled = 1955, WRN_MultipleRuntimeImplementationMatches = 1956, WRN_MultipleRuntimeOverrideMatches = 1957, ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958, ERR_InvalidConstantDeclarationType = 1959, ERR_IllegalVarianceSyntax = 1960, ERR_UnexpectedVariance = 1961, ERR_BadDynamicTypeof = 1962, ERR_ExpressionTreeContainsDynamicOperation = 1963, ERR_BadDynamicConversion = 1964, ERR_DeriveFromDynamic = 1965, ERR_DeriveFromConstructedDynamic = 1966, ERR_DynamicTypeAsBound = 1967, ERR_ConstructedDynamicTypeAsBound = 1968, ERR_DynamicRequiredTypesMissing = 1969, ERR_ExplicitDynamicAttr = 1970, ERR_NoDynamicPhantomOnBase = 1971, ERR_NoDynamicPhantomOnBaseIndexer = 1972, ERR_BadArgTypeDynamicExtension = 1973, WRN_DynamicDispatchToConditionalMethod = 1974, ERR_NoDynamicPhantomOnBaseCtor = 1975, ERR_BadDynamicMethodArgMemgrp = 1976, ERR_BadDynamicMethodArgLambda = 1977, ERR_BadDynamicMethodArg = 1978, ERR_BadDynamicQuery = 1979, ERR_DynamicAttributeMissing = 1980, WRN_IsDynamicIsConfusing = 1981, //ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn. ERR_BadAsyncReturn = 1983, ERR_BadAwaitInFinally = 1984, ERR_BadAwaitInCatch = 1985, ERR_BadAwaitArg = 1986, ERR_BadAsyncArgType = 1988, ERR_BadAsyncExpressionTree = 1989, //ERR_WindowsRuntimeTypesMissing = 1990, // unused in Roslyn ERR_MixingWinRTEventWithRegular = 1991, ERR_BadAwaitWithoutAsync = 1992, //ERR_MissingAsyncTypes = 1993, // unused in Roslyn ERR_BadAsyncLacksBody = 1994, ERR_BadAwaitInQuery = 1995, ERR_BadAwaitInLock = 1996, ERR_TaskRetNoObjectRequired = 1997, WRN_AsyncLacksAwaits = 1998, ERR_FileNotFound = 2001, WRN_FileAlreadyIncluded = 2002, //ERR_DuplicateResponseFile = 2003, ERR_NoFileSpec = 2005, ERR_SwitchNeedsString = 2006, ERR_BadSwitch = 2007, WRN_NoSources = 2008, ERR_OpenResponseFile = 2011, ERR_CantOpenFileWrite = 2012, ERR_BadBaseNumber = 2013, // WRN_UseNewSwitch = 2014, //unused. ERR_BinaryFile = 2015, FTL_BadCodepage = 2016, ERR_NoMainOnDLL = 2017, //FTL_NoMessagesDLL = 2018, FTL_InvalidTarget = 2019, //ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once! FTL_InvalidInputFileName = 2021, //ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once! WRN_NoConfigNotOnCommandLine = 2023, ERR_InvalidFileAlignment = 2024, //ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn. //ERR_SourceMapFileBinary = 2027, WRN_DefineIdentifierRequired = 2029, //ERR_InvalidSourceMap = 2030, //ERR_NoSourceMapFile = 2031, //ERR_IllegalOptionChar = 2032, FTL_OutputFileExists = 2033, ERR_OneAliasPerReference = 2034, ERR_SwitchNeedsNumber = 2035, ERR_MissingDebugSwitch = 2036, ERR_ComRefCallInExpressionTree = 2037, WRN_BadUILang = 2038, ERR_InvalidFormatForGuidForOption = 2039, ERR_MissingGuidForOption = 2040, ERR_InvalidOutputName = 2041, ERR_InvalidDebugInformationFormat = 2042, ERR_LegacyObjectIdSyntax = 2043, ERR_SourceLinkRequiresPdb = 2044, ERR_CannotEmbedWithoutPdb = 2045, ERR_BadSwitchValue = 2046, // unused 2047-2999 WRN_CLS_NoVarArgs = 3000, WRN_CLS_BadArgType = 3001, // Requires SymbolDistinguisher. WRN_CLS_BadReturnType = 3002, WRN_CLS_BadFieldPropType = 3003, // WRN_CLS_BadUnicode = 3004, //unused WRN_CLS_BadIdentifierCase = 3005, WRN_CLS_OverloadRefOut = 3006, WRN_CLS_OverloadUnnamed = 3007, WRN_CLS_BadIdentifier = 3008, WRN_CLS_BadBase = 3009, WRN_CLS_BadInterfaceMember = 3010, WRN_CLS_NoAbstractMembers = 3011, WRN_CLS_NotOnModules = 3012, WRN_CLS_ModuleMissingCLS = 3013, WRN_CLS_AssemblyNotCLS = 3014, WRN_CLS_BadAttributeType = 3015, WRN_CLS_ArrayArgumentToAttribute = 3016, WRN_CLS_NotOnModules2 = 3017, WRN_CLS_IllegalTrueInFalse = 3018, WRN_CLS_MeaninglessOnPrivateType = 3019, WRN_CLS_AssemblyNotCLS2 = 3021, WRN_CLS_MeaninglessOnParam = 3022, WRN_CLS_MeaninglessOnReturn = 3023, WRN_CLS_BadTypeVar = 3024, WRN_CLS_VolatileField = 3026, WRN_CLS_BadInterface = 3027, FTL_BadChecksumAlgorithm = 3028, #endregion diagnostics introduced in C# 4 and earlier // unused 3029-3999 #region diagnostics introduced in C# 5 // 4000 unused ERR_BadAwaitArgIntrinsic = 4001, // 4002 unused ERR_BadAwaitAsIdentifier = 4003, ERR_AwaitInUnsafeContext = 4004, ERR_UnsafeAsyncArgType = 4005, ERR_VarargsAsync = 4006, ERR_ByRefTypeAndAwait = 4007, ERR_BadAwaitArgVoidCall = 4008, ERR_NonTaskMainCantBeAsync = 4009, ERR_CantConvAsyncAnonFuncReturns = 4010, ERR_BadAwaiterPattern = 4011, ERR_BadSpecialByRefLocal = 4012, ERR_SpecialByRefInLambda = 4013, WRN_UnobservedAwaitableExpression = 4014, ERR_SynchronizedAsyncMethod = 4015, ERR_BadAsyncReturnExpression = 4016, ERR_NoConversionForCallerLineNumberParam = 4017, ERR_NoConversionForCallerFilePathParam = 4018, ERR_NoConversionForCallerMemberNameParam = 4019, ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020, ERR_BadCallerFilePathParamWithoutDefaultValue = 4021, ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022, ERR_BadPrefer32OnLib = 4023, WRN_CallerLineNumberParamForUnconsumedLocation = 4024, WRN_CallerFilePathParamForUnconsumedLocation = 4025, WRN_CallerMemberNameParamForUnconsumedLocation = 4026, ERR_DoesntImplementAwaitInterface = 4027, ERR_BadAwaitArg_NeedSystem = 4028, ERR_CantReturnVoid = 4029, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031, ERR_BadAwaitWithoutAsyncMethod = 4032, ERR_BadAwaitWithoutVoidAsyncMethod = 4033, ERR_BadAwaitWithoutAsyncLambda = 4034, // ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn ERR_NoSuchMemberOrExtensionNeedUsing = 4036, #endregion diagnostics introduced in C# 5 // unused 4037-4999 #region diagnostics introduced in C# 6 // WRN_UnknownOption = 5000, //unused in Roslyn ERR_NoEntryPoint = 5001, // huge gap here; available 5002-6999 ERR_UnexpectedAliasedName = 7000, ERR_UnexpectedGenericName = 7002, ERR_UnexpectedUnboundGenericName = 7003, ERR_GlobalStatement = 7006, ERR_BadUsingType = 7007, ERR_ReservedAssemblyName = 7008, ERR_PPReferenceFollowsToken = 7009, ERR_ExpectedPPFile = 7010, ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011, ERR_NameNotInContextPossibleMissingReference = 7012, ERR_MetadataNameTooLong = 7013, ERR_AttributesNotAllowed = 7014, ERR_ExternAliasNotAllowed = 7015, ERR_ConflictingAliasAndDefinition = 7016, ERR_GlobalDefinitionOrStatementExpected = 7017, ERR_ExpectedSingleScript = 7018, ERR_RecursivelyTypedVariable = 7019, ERR_YieldNotAllowedInScript = 7020, ERR_NamespaceNotAllowedInScript = 7021, WRN_MainIgnored = 7022, WRN_StaticInAsOrIs = 7023, ERR_InvalidDelegateType = 7024, ERR_BadVisEventType = 7025, ERR_GlobalAttributesNotAllowed = 7026, ERR_PublicKeyFileFailure = 7027, ERR_PublicKeyContainerFailure = 7028, ERR_FriendRefSigningMismatch = 7029, ERR_CannotPassNullForFriendAssembly = 7030, ERR_SignButNoPrivateKey = 7032, WRN_DelaySignButNoKey = 7033, ERR_InvalidVersionFormat = 7034, WRN_InvalidVersionFormat = 7035, ERR_NoCorrespondingArgument = 7036, // Moot: WRN_DestructorIsNotFinalizer = 7037, ERR_ModuleEmitFailure = 7038, // ERR_NameIllegallyOverrides2 = 7039, // Not used anymore due to 'Single Meaning' relaxation changes // ERR_NameIllegallyOverrides3 = 7040, // Not used anymore due to 'Single Meaning' relaxation changes ERR_ResourceFileNameNotUnique = 7041, ERR_DllImportOnGenericMethod = 7042, ERR_EncUpdateFailedMissingAttribute = 7043, ERR_ParameterNotValidForType = 7045, ERR_AttributeParameterRequired1 = 7046, ERR_AttributeParameterRequired2 = 7047, ERR_SecurityAttributeMissingAction = 7048, ERR_SecurityAttributeInvalidAction = 7049, ERR_SecurityAttributeInvalidActionAssembly = 7050, ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051, ERR_PrincipalPermissionInvalidAction = 7052, ERR_FeatureNotValidInExpressionTree = 7053, ERR_MarshalUnmanagedTypeNotValidForFields = 7054, ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055, ERR_PermissionSetAttributeInvalidFile = 7056, ERR_PermissionSetAttributeFileReadError = 7057, ERR_InvalidVersionFormat2 = 7058, ERR_InvalidAssemblyCultureForExe = 7059, //ERR_AsyncBeforeVersionFive = 7060, ERR_DuplicateAttributeInNetModule = 7061, //WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning ERR_CantOpenIcon = 7064, ERR_ErrorBuildingWin32Resources = 7065, // ERR_IteratorInInteractive = 7066, ERR_BadAttributeParamDefaultArgument = 7067, ERR_MissingTypeInSource = 7068, ERR_MissingTypeInAssembly = 7069, ERR_SecurityAttributeInvalidTarget = 7070, ERR_InvalidAssemblyName = 7071, //ERR_PartialTypesBeforeVersionTwo = 7072, //ERR_PartialMethodsBeforeVersionThree = 7073, //ERR_QueryBeforeVersionThree = 7074, //ERR_AnonymousTypeBeforeVersionThree = 7075, //ERR_ImplicitArrayBeforeVersionThree = 7076, //ERR_ObjectInitializerBeforeVersionThree = 7077, //ERR_LambdaBeforeVersionThree = 7078, ERR_NoTypeDefFromModule = 7079, WRN_CallerFilePathPreferredOverCallerMemberName = 7080, WRN_CallerLineNumberPreferredOverCallerMemberName = 7081, WRN_CallerLineNumberPreferredOverCallerFilePath = 7082, ERR_InvalidDynamicCondition = 7083, ERR_WinRtEventPassedByRef = 7084, //ERR_ByRefReturnUnsupported = 7085, ERR_NetModuleNameMismatch = 7086, ERR_BadModuleName = 7087, ERR_BadCompilationOptionValue = 7088, ERR_BadAppConfigPath = 7089, WRN_AssemblyAttributeFromModuleIsOverridden = 7090, ERR_CmdOptionConflictsSource = 7091, ERR_FixedBufferTooManyDimensions = 7092, ERR_CantReadConfigFile = 7093, ERR_BadAwaitInCatchFilter = 7094, WRN_FilterIsConstantTrue = 7095, ERR_EncNoPIAReference = 7096, //ERR_EncNoDynamicOperation = 7097, // dynamic operations are now allowed ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 7098, ERR_MetadataReferencesNotSupported = 7099, ERR_InvalidAssemblyCulture = 7100, ERR_EncReferenceToAddedMember = 7101, ERR_MutuallyExclusiveOptions = 7102, ERR_InvalidDebugInfo = 7103, #endregion diagnostics introduced in C# 6 // unused 7104-8000 #region more diagnostics introduced in Roslyn (C# 6) WRN_UnimplementedCommandLineSwitch = 8001, WRN_ReferencedAssemblyDoesNotHaveStrongName = 8002, ERR_InvalidSignaturePublicKey = 8003, ERR_ExportedTypeConflictsWithDeclaration = 8004, ERR_ExportedTypesConflict = 8005, ERR_ForwardedTypeConflictsWithDeclaration = 8006, ERR_ForwardedTypesConflict = 8007, ERR_ForwardedTypeConflictsWithExportedType = 8008, WRN_RefCultureMismatch = 8009, ERR_AgnosticToMachineModule = 8010, ERR_ConflictingMachineModule = 8011, WRN_ConflictingMachineAssembly = 8012, ERR_CryptoHashFailed = 8013, ERR_MissingNetModuleReference = 8014, ERR_NetModuleNameMustBeUnique = 8015, ERR_UnsupportedTransparentIdentifierAccess = 8016, ERR_ParamDefaultValueDiffersFromAttribute = 8017, WRN_UnqualifiedNestedTypeInCref = 8018, HDN_UnusedUsingDirective = 8019, HDN_UnusedExternAlias = 8020, WRN_NoRuntimeMetadataVersion = 8021, ERR_FeatureNotAvailableInVersion1 = 8022, // Note: one per version to make telemetry easier ERR_FeatureNotAvailableInVersion2 = 8023, ERR_FeatureNotAvailableInVersion3 = 8024, ERR_FeatureNotAvailableInVersion4 = 8025, ERR_FeatureNotAvailableInVersion5 = 8026, // ERR_FeatureNotAvailableInVersion6 is below ERR_FieldHasMultipleDistinctConstantValues = 8027, ERR_ComImportWithInitializers = 8028, WRN_PdbLocalNameTooLong = 8029, ERR_RetNoObjectRequiredLambda = 8030, ERR_TaskRetNoObjectRequiredLambda = 8031, WRN_AnalyzerCannotBeCreated = 8032, WRN_NoAnalyzerInAssembly = 8033, WRN_UnableToLoadAnalyzer = 8034, ERR_CantReadRulesetFile = 8035, ERR_BadPdbData = 8036, // available 8037-8039 INF_UnableToLoadSomeTypesInAnalyzer = 8040, // available 8041-8049 ERR_InitializerOnNonAutoProperty = 8050, ERR_AutoPropertyMustHaveGetAccessor = 8051, // ERR_AutoPropertyInitializerInInterface = 8052, ERR_InstancePropertyInitializerInInterface = 8053, ERR_EnumsCantContainDefaultConstructor = 8054, ERR_EncodinglessSyntaxTree = 8055, // ERR_AccessorListAndExpressionBody = 8056, Deprecated in favor of ERR_BlockBodyAndExpressionBody ERR_BlockBodyAndExpressionBody = 8057, ERR_FeatureIsExperimental = 8058, ERR_FeatureNotAvailableInVersion6 = 8059, // available 8062-8069 ERR_SwitchFallOut = 8070, // available = 8071, ERR_NullPropagatingOpInExpressionTree = 8072, WRN_NubExprIsConstBool2 = 8073, ERR_DictionaryInitializerInExpressionTree = 8074, ERR_ExtensionCollectionElementInitializerInExpressionTree = 8075, ERR_UnclosedExpressionHole = 8076, ERR_SingleLineCommentInExpressionHole = 8077, ERR_InsufficientStack = 8078, ERR_UseDefViolationProperty = 8079, ERR_AutoPropertyMustOverrideSet = 8080, ERR_ExpressionHasNoName = 8081, ERR_SubexpressionNotInNameof = 8082, ERR_AliasQualifiedNameNotAnExpression = 8083, ERR_NameofMethodGroupWithTypeParameters = 8084, ERR_NoAliasHere = 8085, ERR_UnescapedCurly = 8086, ERR_EscapedCurly = 8087, ERR_TrailingWhitespaceInFormatSpecifier = 8088, ERR_EmptyFormatSpecifier = 8089, ERR_ErrorInReferencedAssembly = 8090, ERR_ExternHasConstructorInitializer = 8091, ERR_ExpressionOrDeclarationExpected = 8092, ERR_NameofExtensionMethod = 8093, WRN_AlignmentMagnitude = 8094, ERR_ConstantStringTooLong = 8095, ERR_DebugEntryPointNotSourceMethodDefinition = 8096, ERR_LoadDirectiveOnlyAllowedInScripts = 8097, ERR_PPLoadFollowsToken = 8098, ERR_SourceFileReferencesNotSupported = 8099, ERR_BadAwaitInStaticVariableInitializer = 8100, ERR_InvalidPathMap = 8101, ERR_PublicSignButNoKey = 8102, ERR_TooManyUserStrings = 8103, ERR_PeWritingFailure = 8104, #endregion diagnostics introduced in Roslyn (C# 6) #region diagnostics introduced in C# 6 updates WRN_AttributeIgnoredWhenPublicSigning = 8105, ERR_OptionMustBeAbsolutePath = 8106, #endregion diagnostics introduced in C# 6 updates ERR_FeatureNotAvailableInVersion7 = 8107, #region diagnostics for local functions introduced in C# 7 ERR_DynamicLocalFunctionParamsParameter = 8108, ERR_ExpressionTreeContainsLocalFunction = 8110, #endregion diagnostics for local functions introduced in C# 7 #region diagnostics for instrumentation ERR_InvalidInstrumentationKind = 8111, #endregion ERR_LocalFunctionMissingBody = 8112, ERR_InvalidHashAlgorithmName = 8113, // Unused 8113, 8114, 8115 #region diagnostics for pattern-matching introduced in C# 7 ERR_ThrowMisplaced = 8115, ERR_PatternNullableType = 8116, ERR_BadPatternExpression = 8117, ERR_SwitchExpressionValueExpected = 8119, ERR_SwitchCaseSubsumed = 8120, ERR_PatternWrongType = 8121, ERR_ExpressionTreeContainsIsMatch = 8122, #endregion diagnostics for pattern-matching introduced in C# 7 #region tuple diagnostics introduced in C# 7 WRN_TupleLiteralNameMismatch = 8123, ERR_TupleTooFewElements = 8124, ERR_TupleReservedElementName = 8125, ERR_TupleReservedElementNameAnyPosition = 8126, ERR_TupleDuplicateElementName = 8127, ERR_PredefinedTypeMemberNotFoundInAssembly = 8128, ERR_MissingDeconstruct = 8129, ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable = 8130, ERR_DeconstructRequiresExpression = 8131, ERR_DeconstructWrongCardinality = 8132, ERR_CannotDeconstructDynamic = 8133, ERR_DeconstructTooFewElements = 8134, ERR_ConversionNotTupleCompatible = 8135, ERR_DeconstructionVarFormDisallowsSpecificType = 8136, ERR_TupleElementNamesAttributeMissing = 8137, ERR_ExplicitTupleElementNamesAttribute = 8138, ERR_CantChangeTupleNamesOnOverride = 8139, ERR_DuplicateInterfaceWithTupleNamesInBaseList = 8140, ERR_ImplBadTupleNames = 8141, ERR_PartialMethodInconsistentTupleNames = 8142, ERR_ExpressionTreeContainsTupleLiteral = 8143, ERR_ExpressionTreeContainsTupleConversion = 8144, #endregion tuple diagnostics introduced in C# 7 #region diagnostics for ref locals and ref returns introduced in C# 7 ERR_AutoPropertyCannotBeRefReturning = 8145, ERR_RefPropertyMustHaveGetAccessor = 8146, ERR_RefPropertyCannotHaveSetAccessor = 8147, ERR_CantChangeRefReturnOnOverride = 8148, ERR_MustNotHaveRefReturn = 8149, ERR_MustHaveRefReturn = 8150, ERR_RefReturnMustHaveIdentityConversion = 8151, ERR_CloseUnimplementedInterfaceMemberWrongRefReturn = 8152, ERR_RefReturningCallInExpressionTree = 8153, ERR_BadIteratorReturnRef = 8154, ERR_BadRefReturnExpressionTree = 8155, ERR_RefReturnLvalueExpected = 8156, ERR_RefReturnNonreturnableLocal = 8157, ERR_RefReturnNonreturnableLocal2 = 8158, ERR_RefReturnRangeVariable = 8159, ERR_RefReturnReadonly = 8160, ERR_RefReturnReadonlyStatic = 8161, ERR_RefReturnReadonly2 = 8162, ERR_RefReturnReadonlyStatic2 = 8163, // ERR_RefReturnCall = 8164, we use more general ERR_EscapeCall now // ERR_RefReturnCall2 = 8165, we use more general ERR_EscapeCall2 now ERR_RefReturnParameter = 8166, ERR_RefReturnParameter2 = 8167, ERR_RefReturnLocal = 8168, ERR_RefReturnLocal2 = 8169, ERR_RefReturnStructThis = 8170, ERR_InitializeByValueVariableWithReference = 8171, ERR_InitializeByReferenceVariableWithValue = 8172, ERR_RefAssignmentMustHaveIdentityConversion = 8173, ERR_ByReferenceVariableMustBeInitialized = 8174, ERR_AnonDelegateCantUseLocal = 8175, ERR_BadIteratorLocalType = 8176, ERR_BadAsyncLocalType = 8177, ERR_RefReturningCallAndAwait = 8178, #endregion diagnostics for ref locals and ref returns introduced in C# 7 #region stragglers for C# 7 ERR_PredefinedValueTupleTypeNotFound = 8179, // We need a specific error code for ValueTuple as an IDE codefix depends on it (AddNuget) ERR_SemiOrLBraceOrArrowExpected = 8180, ERR_NewWithTupleTypeSyntax = 8181, ERR_PredefinedValueTupleTypeMustBeStruct = 8182, ERR_DiscardTypeInferenceFailed = 8183, // ERR_MixedDeconstructionUnsupported = 8184, ERR_DeclarationExpressionNotPermitted = 8185, ERR_MustDeclareForeachIteration = 8186, ERR_TupleElementNamesInDeconstruction = 8187, ERR_ExpressionTreeContainsThrowExpression = 8188, ERR_DelegateRefMismatch = 8189, #endregion stragglers for C# 7 #region diagnostics for parse options ERR_BadSourceCodeKind = 8190, ERR_BadDocumentationMode = 8191, ERR_BadLanguageVersion = 8192, #endregion // Unused 8193-8195 #region diagnostics for out var ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList = 8196, ERR_TypeInferenceFailedForImplicitlyTypedOutVariable = 8197, ERR_ExpressionTreeContainsOutVariable = 8198, #endregion diagnostics for out var #region more stragglers for C# 7 ERR_VarInvocationLvalueReserved = 8199, //ERR_ExpressionVariableInConstructorOrFieldInitializer = 8200, //ERR_ExpressionVariableInQueryClause = 8201, ERR_PublicSignNetModule = 8202, ERR_BadAssemblyName = 8203, ERR_BadAsyncMethodBuilderTaskProperty = 8204, // ERR_AttributesInLocalFuncDecl = 8205, ERR_TypeForwardedToMultipleAssemblies = 8206, ERR_ExpressionTreeContainsDiscard = 8207, ERR_PatternDynamicType = 8208, ERR_VoidAssignment = 8209, ERR_VoidInTuple = 8210, #endregion more stragglers for C# 7 #region diagnostics introduced for C# 7.1 ERR_Merge_conflict_marker_encountered = 8300, ERR_InvalidPreprocessingSymbol = 8301, ERR_FeatureNotAvailableInVersion7_1 = 8302, ERR_LanguageVersionCannotHaveLeadingZeroes = 8303, ERR_CompilerAndLanguageVersion = 8304, WRN_Experimental = 8305, ERR_TupleInferredNamesNotAvailable = 8306, ERR_TypelessTupleInAs = 8307, ERR_NoRefOutWhenRefOnly = 8308, ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 8309, ERR_BadOpOnNullOrDefaultOrNew = 8310, // ERR_BadDynamicMethodArgDefaultLiteral = 8311, ERR_DefaultLiteralNotValid = 8312, // ERR_DefaultInSwitch = 8313, ERR_PatternWrongGenericTypeInVersion = 8314, ERR_AmbigBinaryOpsOnDefault = 8315, #endregion diagnostics introduced for C# 7.1 #region diagnostics introduced for C# 7.2 ERR_FeatureNotAvailableInVersion7_2 = 8320, WRN_UnreferencedLocalFunction = 8321, ERR_DynamicLocalFunctionTypeParameter = 8322, ERR_BadNonTrailingNamedArgument = 8323, ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation = 8324, #endregion diagnostics introduced for C# 7.2 #region diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2 ERR_RefConditionalAndAwait = 8325, ERR_RefConditionalNeedsTwoRefs = 8326, ERR_RefConditionalDifferentTypes = 8327, ERR_BadParameterModifiers = 8328, ERR_RefReadonlyNotField = 8329, ERR_RefReadonlyNotField2 = 8330, ERR_AssignReadonlyNotField = 8331, ERR_AssignReadonlyNotField2 = 8332, ERR_RefReturnReadonlyNotField = 8333, ERR_RefReturnReadonlyNotField2 = 8334, ERR_ExplicitReservedAttr = 8335, ERR_TypeReserved = 8336, ERR_RefExtensionMustBeValueTypeOrConstrainedToOne = 8337, ERR_InExtensionMustBeValueType = 8338, // ERR_BadParameterModifiersOrder = 8339, // Modifier ordering is relaxed ERR_FieldsInRoStruct = 8340, ERR_AutoPropsInRoStruct = 8341, ERR_FieldlikeEventsInRoStruct = 8342, ERR_RefStructInterfaceImpl = 8343, ERR_BadSpecialByRefIterator = 8344, ERR_FieldAutoPropCantBeByRefLike = 8345, ERR_StackAllocConversionNotPossible = 8346, ERR_EscapeCall = 8347, ERR_EscapeCall2 = 8348, ERR_EscapeOther = 8349, ERR_CallArgMixing = 8350, ERR_MismatchedRefEscapeInTernary = 8351, ERR_EscapeLocal = 8352, ERR_EscapeStackAlloc = 8353, ERR_RefReturnThis = 8354, ERR_OutAttrOnInParam = 8355, #endregion diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2 ERR_PredefinedValueTupleTypeAmbiguous3 = 8356, ERR_InvalidVersionFormatDeterministic = 8357, ERR_AttributeCtorInParameter = 8358, #region diagnostics for FilterIsConstant warning message fix WRN_FilterIsConstantFalse = 8359, WRN_FilterIsConstantFalseRedundantTryCatch = 8360, #endregion diagnostics for FilterIsConstant warning message fix ERR_ConditionalInInterpolation = 8361, ERR_CantUseVoidInArglist = 8362, ERR_InDynamicMethodArg = 8364, #region diagnostics introduced for C# 7.3 ERR_FeatureNotAvailableInVersion7_3 = 8370, WRN_AttributesOnBackingFieldsNotAvailable = 8371, ERR_DoNotUseFixedBufferAttrOnProperty = 8372, ERR_RefLocalOrParamExpected = 8373, ERR_RefAssignNarrower = 8374, ERR_NewBoundWithUnmanaged = 8375, //ERR_UnmanagedConstraintMustBeFirst = 8376, ERR_UnmanagedConstraintNotSatisfied = 8377, ERR_CantUseInOrOutInArglist = 8378, ERR_ConWithUnmanagedCon = 8379, ERR_UnmanagedBoundWithClass = 8380, ERR_InvalidStackAllocArray = 8381, ERR_ExpressionTreeContainsTupleBinOp = 8382, WRN_TupleBinopLiteralNameMismatch = 8383, ERR_TupleSizesMismatchForBinOps = 8384, ERR_ExprCannotBeFixed = 8385, ERR_InvalidObjectCreation = 8386, #endregion diagnostics introduced for C# 7.3 WRN_TypeParameterSameAsOuterMethodTypeParameter = 8387, ERR_OutVariableCannotBeByRef = 8388, ERR_OmittedTypeArgument = 8389, #region diagnostics introduced for C# 8.0 ERR_FeatureNotAvailableInVersion8 = 8400, ERR_AltInterpolatedVerbatimStringsNotAvailable = 8401, // Unused 8402 ERR_IteratorMustBeAsync = 8403, ERR_NoConvToIAsyncDisp = 8410, ERR_AwaitForEachMissingMember = 8411, ERR_BadGetAsyncEnumerator = 8412, ERR_MultipleIAsyncEnumOfT = 8413, ERR_ForEachMissingMemberWrongAsync = 8414, ERR_AwaitForEachMissingMemberWrongAsync = 8415, ERR_BadDynamicAwaitForEach = 8416, ERR_NoConvToIAsyncDispWrongAsync = 8417, ERR_NoConvToIDispWrongAsync = 8418, ERR_PossibleAsyncIteratorWithoutYield = 8419, ERR_PossibleAsyncIteratorWithoutYieldOrAwait = 8420, ERR_StaticLocalFunctionCannotCaptureVariable = 8421, ERR_StaticLocalFunctionCannotCaptureThis = 8422, ERR_AttributeNotOnEventAccessor = 8423, WRN_UnconsumedEnumeratorCancellationAttributeUsage = 8424, WRN_UndecoratedCancellationTokenParameter = 8425, ERR_MultipleEnumeratorCancellationAttributes = 8426, ERR_VarianceInterfaceNesting = 8427, ERR_ImplicitIndexIndexerWithName = 8428, ERR_ImplicitRangeIndexerWithName = 8429, // available range #region diagnostics introduced for recursive patterns ERR_WrongNumberOfSubpatterns = 8502, ERR_PropertyPatternNameMissing = 8503, ERR_MissingPattern = 8504, ERR_DefaultPattern = 8505, ERR_SwitchExpressionNoBestType = 8506, // ERR_SingleElementPositionalPatternRequiresDisambiguation = 8507, // Retired C# 8 diagnostic ERR_VarMayNotBindToType = 8508, WRN_SwitchExpressionNotExhaustive = 8509, ERR_SwitchArmSubsumed = 8510, ERR_ConstantPatternVsOpenType = 8511, WRN_CaseConstantNamedUnderscore = 8512, WRN_IsTypeNamedUnderscore = 8513, ERR_ExpressionTreeContainsSwitchExpression = 8514, ERR_SwitchGoverningExpressionRequiresParens = 8515, ERR_TupleElementNameMismatch = 8516, ERR_DeconstructParameterNameMismatch = 8517, ERR_IsPatternImpossible = 8518, WRN_GivenExpressionNeverMatchesPattern = 8519, WRN_GivenExpressionAlwaysMatchesConstant = 8520, ERR_PointerTypeInPatternMatching = 8521, ERR_ArgumentNameInITuplePattern = 8522, ERR_DiscardPatternInSwitchStatement = 8523, WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue = 8524, // available 8525-8596 #endregion diagnostics introduced for recursive patterns WRN_ThrowPossibleNull = 8597, ERR_IllegalSuppression = 8598, // available 8599, WRN_ConvertingNullableToNonNullable = 8600, WRN_NullReferenceAssignment = 8601, WRN_NullReferenceReceiver = 8602, WRN_NullReferenceReturn = 8603, WRN_NullReferenceArgument = 8604, WRN_UnboxPossibleNull = 8605, // WRN_NullReferenceIterationVariable = 8606 (unavailable, may be used in warning suppressions in early C# 8.0 code) WRN_DisallowNullAttributeForbidsMaybeNullAssignment = 8607, WRN_NullabilityMismatchInTypeOnOverride = 8608, WRN_NullabilityMismatchInReturnTypeOnOverride = 8609, WRN_NullabilityMismatchInParameterTypeOnOverride = 8610, WRN_NullabilityMismatchInParameterTypeOnPartial = 8611, WRN_NullabilityMismatchInTypeOnImplicitImplementation = 8612, WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation = 8613, WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation = 8614, WRN_NullabilityMismatchInTypeOnExplicitImplementation = 8615, WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation = 8616, WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation = 8617, WRN_UninitializedNonNullableField = 8618, WRN_NullabilityMismatchInAssignment = 8619, WRN_NullabilityMismatchInArgument = 8620, WRN_NullabilityMismatchInReturnTypeOfTargetDelegate = 8621, WRN_NullabilityMismatchInParameterTypeOfTargetDelegate = 8622, ERR_ExplicitNullableAttribute = 8623, WRN_NullabilityMismatchInArgumentForOutput = 8624, WRN_NullAsNonNullable = 8625, //WRN_AsOperatorMayReturnNull = 8626, ERR_NullableUnconstrainedTypeParameter = 8627, ERR_AnnotationDisallowedInObjectCreation = 8628, WRN_NullableValueTypeMayBeNull = 8629, ERR_NullableOptionNotAvailable = 8630, WRN_NullabilityMismatchInTypeParameterConstraint = 8631, WRN_MissingNonNullTypesContextForAnnotation = 8632, WRN_NullabilityMismatchInConstraintsOnImplicitImplementation = 8633, WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint = 8634, ERR_TripleDotNotAllowed = 8635, ERR_BadNullableContextOption = 8636, ERR_NullableDirectiveQualifierExpected = 8637, //WRN_ConditionalAccessMayReturnNull = 8638, ERR_BadNullableTypeof = 8639, ERR_ExpressionTreeCantContainRefStruct = 8640, ERR_ElseCannotStartStatement = 8641, ERR_ExpressionTreeCantContainNullCoalescingAssignment = 8642, WRN_NullabilityMismatchInExplicitlyImplementedInterface = 8643, WRN_NullabilityMismatchInInterfaceImplementedByBase = 8644, WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList = 8645, ERR_DuplicateExplicitImpl = 8646, ERR_UsingVarInSwitchCase = 8647, ERR_GoToForwardJumpOverUsingVar = 8648, ERR_GoToBackwardJumpOverUsingVar = 8649, ERR_IsNullableType = 8650, ERR_AsNullableType = 8651, ERR_FeatureInPreview = 8652, //WRN_DefaultExpressionMayIntroduceNullT = 8653, //WRN_NullLiteralMayIntroduceNullT = 8654, WRN_SwitchExpressionNotExhaustiveForNull = 8655, WRN_ImplicitCopyInReadOnlyMember = 8656, ERR_StaticMemberCantBeReadOnly = 8657, ERR_AutoSetterCantBeReadOnly = 8658, ERR_AutoPropertyWithSetterCantBeReadOnly = 8659, ERR_InvalidPropertyReadOnlyMods = 8660, ERR_DuplicatePropertyReadOnlyMods = 8661, ERR_FieldLikeEventCantBeReadOnly = 8662, ERR_PartialMethodReadOnlyDifference = 8663, ERR_ReadOnlyModMissingAccessor = 8664, ERR_OverrideRefConstraintNotSatisfied = 8665, ERR_OverrideValConstraintNotSatisfied = 8666, WRN_NullabilityMismatchInConstraintsOnPartialImplementation = 8667, ERR_NullableDirectiveTargetExpected = 8668, WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode = 8669, WRN_NullReferenceInitializer = 8670, ERR_MultipleAnalyzerConfigsInSameDir = 8700, ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 8701, ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember = 8702, ERR_InvalidModifierForLanguageVersion = 8703, ERR_ImplicitImplementationOfNonPublicInterfaceMember = 8704, ERR_MostSpecificImplementationIsNotFound = 8705, ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember = 8706, ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 8707, //ERR_NotBaseOrImplementedInterface = 8708, //ERR_NotImplementedInBase = 8709, //ERR_NotDeclaredInBase = 8710, ERR_DefaultInterfaceImplementationInNoPIAType = 8711, ERR_AbstractEventHasAccessors = 8712, //ERR_NotNullConstraintMustBeFirst = 8713, WRN_NullabilityMismatchInTypeParameterNotNullConstraint = 8714, ERR_DuplicateNullSuppression = 8715, ERR_DefaultLiteralNoTargetType = 8716, ERR_ReAbstractionInNoPIAType = 8750, #endregion diagnostics introduced for C# 8.0 #region diagnostics introduced in C# 9.0 ERR_InternalError = 8751, ERR_ImplicitObjectCreationIllegalTargetType = 8752, ERR_ImplicitObjectCreationNotValid = 8753, ERR_ImplicitObjectCreationNoTargetType = 8754, ERR_BadFuncPointerParamModifier = 8755, ERR_BadFuncPointerArgCount = 8756, ERR_MethFuncPtrMismatch = 8757, ERR_FuncPtrRefMismatch = 8758, ERR_FuncPtrMethMustBeStatic = 8759, ERR_ExternEventInitializer = 8760, ERR_AmbigBinaryOpsOnUnconstrainedDefault = 8761, WRN_ParameterConditionallyDisallowsNull = 8762, WRN_ShouldNotReturn = 8763, WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride = 8764, WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride = 8765, WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation = 8766, WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation = 8767, WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation = 8768, WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation = 8769, WRN_DoesNotReturnMismatch = 8770, ERR_NoOutputDirectory = 8771, ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 8772, ERR_FeatureNotAvailableInVersion9 = 8773, WRN_MemberNotNull = 8774, WRN_MemberNotNullWhen = 8775, WRN_MemberNotNullBadMember = 8776, WRN_ParameterDisallowsNull = 8777, WRN_ConstOutOfRangeChecked = 8778, ERR_DuplicateInterfaceWithDifferencesInBaseList = 8779, ERR_DesignatorBeneathPatternCombinator = 8780, ERR_UnsupportedTypeForRelationalPattern = 8781, ERR_RelationalPatternWithNaN = 8782, ERR_ConditionalOnLocalFunction = 8783, WRN_GeneratorFailedDuringInitialization = 8784, WRN_GeneratorFailedDuringGeneration = 8785, ERR_WrongFuncPtrCallingConvention = 8786, ERR_MissingAddressOf = 8787, ERR_CannotUseReducedExtensionMethodInAddressOf = 8788, ERR_CannotUseFunctionPointerAsFixedLocal = 8789, ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer = 8790, ERR_ExpressionTreeContainsFromEndIndexExpression = 8791, ERR_ExpressionTreeContainsRangeExpression = 8792, WRN_GivenExpressionAlwaysMatchesPattern = 8793, WRN_IsPatternAlways = 8794, ERR_PartialMethodWithAccessibilityModsMustHaveImplementation = 8795, ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods = 8796, ERR_PartialMethodWithOutParamMustHaveAccessMods = 8797, ERR_PartialMethodWithExtendedModMustHaveAccessMods = 8798, ERR_PartialMethodAccessibilityDifference = 8799, ERR_PartialMethodExtendedModDifference = 8800, ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement = 8801, ERR_SimpleProgramMultipleUnitsWithTopLevelStatements = 8802, ERR_TopLevelStatementAfterNamespaceOrType = 8803, ERR_SimpleProgramDisallowsMainType = 8804, ERR_SimpleProgramNotAnExecutable = 8805, ERR_UnsupportedCallingConvention = 8806, ERR_InvalidFunctionPointerCallingConvention = 8807, ERR_InvalidFuncPointerReturnTypeModifier = 8808, ERR_DupReturnTypeMod = 8809, ERR_AddressOfMethodGroupInExpressionTree = 8810, ERR_CannotConvertAddressOfToDelegate = 8811, ERR_AddressOfToNonFunctionPointer = 8812, ERR_ModuleInitializerMethodMustBeOrdinary = 8813, ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType = 8814, ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid = 8815, ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric = 8816, ERR_PartialMethodReturnTypeDifference = 8817, ERR_PartialMethodRefReturnDifference = 8818, WRN_NullabilityMismatchInReturnTypeOnPartial = 8819, ERR_StaticAnonymousFunctionCannotCaptureVariable = 8820, ERR_StaticAnonymousFunctionCannotCaptureThis = 8821, ERR_OverrideDefaultConstraintNotSatisfied = 8822, ERR_DefaultConstraintOverrideOnly = 8823, WRN_ParameterNotNullIfNotNull = 8824, WRN_ReturnNotNullIfNotNull = 8825, WRN_PartialMethodTypeDifference = 8826, ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses = 8830, ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses = 8831, WRN_SwitchExpressionNotExhaustiveWithWhen = 8846, WRN_SwitchExpressionNotExhaustiveForNullWithWhen = 8847, WRN_PrecedenceInversion = 8848, ERR_ExpressionTreeContainsWithExpression = 8849, WRN_AnalyzerReferencesFramework = 8850, // WRN_EqualsWithoutGetHashCode is for object.Equals and works for classes. // WRN_RecordEqualsWithoutGetHashCode is for IEquatable<T>.Equals and works for records. WRN_RecordEqualsWithoutGetHashCode = 8851, ERR_AssignmentInitOnly = 8852, ERR_CantChangeInitOnlyOnOverride = 8853, ERR_CloseUnimplementedInterfaceMemberWrongInitOnly = 8854, ERR_ExplicitPropertyMismatchInitOnly = 8855, ERR_BadInitAccessor = 8856, ERR_InvalidWithReceiverType = 8857, ERR_CannotClone = 8858, ERR_CloneDisallowedInRecord = 8859, WRN_RecordNamedDisallowed = 8860, ERR_UnexpectedArgumentList = 8861, ERR_UnexpectedOrMissingConstructorInitializerInRecord = 8862, ERR_MultipleRecordParameterLists = 8863, ERR_BadRecordBase = 8864, ERR_BadInheritanceFromRecord = 8865, ERR_BadRecordMemberForPositionalParameter = 8866, ERR_NoCopyConstructorInBaseType = 8867, ERR_CopyConstructorMustInvokeBaseCopyConstructor = 8868, ERR_DoesNotOverrideMethodFromObject = 8869, ERR_SealedAPIInRecord = 8870, ERR_DoesNotOverrideBaseMethod = 8871, ERR_NotOverridableAPIInRecord = 8872, ERR_NonPublicAPIInRecord = 8873, ERR_SignatureMismatchInRecord = 8874, ERR_NonProtectedAPIInRecord = 8875, ERR_DoesNotOverrideBaseEqualityContract = 8876, ERR_StaticAPIInRecord = 8877, ERR_CopyConstructorWrongAccessibility = 8878, ERR_NonPrivateAPIInRecord = 8879, // The following warnings correspond to errors of the same name, but are reported // when a definite assignment issue is reported due to private fields imported from metadata. WRN_UnassignedThisAutoProperty = 8880, WRN_UnassignedThis = 8881, WRN_ParamUnassigned = 8882, WRN_UseDefViolationProperty = 8883, WRN_UseDefViolationField = 8884, WRN_UseDefViolationThis = 8885, WRN_UseDefViolationOut = 8886, WRN_UseDefViolation = 8887, ERR_CannotSpecifyManagedWithUnmanagedSpecifiers = 8888, ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv = 8889, ERR_TypeNotFound = 8890, ERR_TypeMustBePublic = 8891, WRN_SyncAndAsyncEntryPoints = 8892, ERR_InvalidUnmanagedCallersOnlyCallConv = 8893, ERR_CannotUseManagedTypeInUnmanagedCallersOnly = 8894, ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric = 8895, ERR_UnmanagedCallersOnlyRequiresStatic = 8896, // The following warnings correspond to errors of the same name, but are reported // as warnings on interface methods and properties due in warning level 5. They // were not reported at all prior to level 5. WRN_ParameterIsStaticClass = 8897, WRN_ReturnTypeIsStaticClass = 8898, ERR_EntryPointCannotBeUnmanagedCallersOnly = 8899, ERR_ModuleInitializerCannotBeUnmanagedCallersOnly = 8900, ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly = 8901, ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate = 8902, ERR_InitCannotBeReadonly = 8903, ERR_UnexpectedVarianceStaticMember = 8904, ERR_FunctionPointersCannotBeCalledWithNamedArguments = 8905, ERR_EqualityContractRequiresGetter = 8906, WRN_UnreadRecordParameter = 8907, ERR_BadFieldTypeInRecord = 8908, WRN_DoNotCompareFunctionPointers = 8909, ERR_RecordAmbigCtor = 8910, ERR_FunctionPointerTypesInAttributeNotSupported = 8911, #endregion diagnostics introduced for C# 9.0 #region diagnostics introduced for C# 10.0 ERR_InheritingFromRecordWithSealedToString = 8912, ERR_HiddenPositionalMember = 8913, ERR_GlobalUsingInNamespace = 8914, ERR_GlobalUsingOutOfOrder = 8915, ERR_AttributesRequireParenthesizedLambdaExpression = 8916, ERR_CannotInferDelegateType = 8917, ERR_InvalidNameInSubpattern = 8918, ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces = 8919, ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers = 8920, ERR_BadAbstractUnaryOperatorSignature = 8921, ERR_BadAbstractIncDecSignature = 8922, ERR_BadAbstractIncDecRetType = 8923, ERR_BadAbstractBinaryOperatorSignature = 8924, ERR_BadAbstractShiftOperatorSignature = 8925, ERR_BadAbstractStaticMemberAccess = 8926, ERR_ExpressionTreeContainsAbstractStaticMemberAccess = 8927, ERR_CloseUnimplementedInterfaceMemberNotStatic = 8928, ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember = 8929, ERR_ExplicitImplementationOfOperatorsMustBeStatic = 8930, ERR_AbstractConversionNotInvolvingContainedType = 8931, ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod = 8932, HDN_DuplicateWithGlobalUsing = 8933, ERR_CantConvAnonMethReturnType = 8934, ERR_BuilderAttributeDisallowed = 8935, ERR_FeatureNotAvailableInVersion10 = 8936, ERR_SimpleProgramIsEmpty = 8937, ERR_LineSpanDirectiveInvalidValue = 8938, ERR_LineSpanDirectiveEndLessThanStart = 8939, ERR_WrongArityAsyncReturn = 8940, ERR_InterpolatedStringHandlerMethodReturnMalformed = 8941, ERR_InterpolatedStringHandlerMethodReturnInconsistent = 8942, ERR_NullInvalidInterpolatedStringHandlerArgumentName = 8943, ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName = 8944, ERR_InvalidInterpolatedStringHandlerArgumentName = 8945, ERR_TypeIsNotAnInterpolatedStringHandlerType = 8946, WRN_ParameterOccursAfterInterpolatedStringHandlerParameter = 8947, ERR_CannotUseSelfAsInterpolatedStringHandlerArgument = 8948, ERR_InterpolatedStringHandlerArgumentAttributeMalformed = 8949, ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString = 8950, ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified = 8951, ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion = 8952, ERR_InterpolatedStringHandlerCreationCannotUseDynamic = 8953, ERR_MultipleFileScopedNamespace = 8954, ERR_FileScopedAndNormalNamespace = 8955, ERR_FileScopedNamespaceNotBeforeAllMembers = 8956, ERR_NoImplicitConvTargetTypedConditional = 8957, ERR_NonPublicParameterlessStructConstructor = 8958, ERR_NoConversionForCallerArgumentExpressionParam = 8959, WRN_CallerLineNumberPreferredOverCallerArgumentExpression = 8960, WRN_CallerFilePathPreferredOverCallerArgumentExpression = 8961, WRN_CallerMemberNamePreferredOverCallerArgumentExpression = 8962, WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 8963, ERR_BadCallerArgumentExpressionParamWithoutDefaultValue = 8964, WRN_CallerArgumentExpressionAttributeSelfReferential = 8965, WRN_CallerArgumentExpressionParamForUnconsumedLocation = 8966, ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString = 8967, #endregion // Note: you will need to re-generate compiler code after adding warnings (eng\generate-compiler-code.cmd) } }
// Licensed to the .NET Foundation under one or more 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 { internal enum ErrorCode { Void = InternalErrorCode.Void, Unknown = InternalErrorCode.Unknown, #region diagnostics introduced in C# 4 and earlier //FTL_InternalError = 1, //FTL_FailedToLoadResource = 2, //FTL_NoMemory = 3, //ERR_WarningAsError = 4, //ERR_MissingOptionArg = 5, ERR_NoMetadataFile = 6, //FTL_ComPlusInit = 7, //FTL_MetadataImportFailure = 8, no longer used in Roslyn. FTL_MetadataCantOpenFile = 9, //ERR_FatalError = 10, //ERR_CantImportBase = 11, ERR_NoTypeDef = 12, //FTL_MetadataEmitFailure = 13, Roslyn does not catch stream writing exceptions. Those are propagated to the caller. //FTL_RequiredFileNotFound = 14, //ERR_ClassNameTooLong = 15, Deprecated in favor of ERR_MetadataNameTooLong. ERR_OutputWriteFailed = 16, ERR_MultipleEntryPoints = 17, //ERR_UnimplementedOp = 18, ERR_BadBinaryOps = 19, ERR_IntDivByZero = 20, ERR_BadIndexLHS = 21, ERR_BadIndexCount = 22, ERR_BadUnaryOp = 23, //ERR_NoStdLib = 25, not used in Roslyn ERR_ThisInStaticMeth = 26, ERR_ThisInBadContext = 27, WRN_InvalidMainSig = 28, ERR_NoImplicitConv = 29, // Requires SymbolDistinguisher. ERR_NoExplicitConv = 30, // Requires SymbolDistinguisher. ERR_ConstOutOfRange = 31, ERR_AmbigBinaryOps = 34, ERR_AmbigUnaryOp = 35, ERR_InAttrOnOutParam = 36, ERR_ValueCantBeNull = 37, //ERR_WrongNestedThis = 38, No longer given in Roslyn. Less specific ERR_ObjectRequired "An object reference is required for the non-static..." ERR_NoExplicitBuiltinConv = 39, // Requires SymbolDistinguisher. //FTL_DebugInit = 40, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. FTL_DebugEmitFailure = 41, //FTL_DebugInitFile = 42, Not used in Roslyn. Roslyn gives ERR_CantOpenFileWrite with specific error info. //FTL_BadPDBFormat = 43, Not used in Roslyn. Roslyn gives FTL_DebugEmitFailure with specific error code info. ERR_BadVisReturnType = 50, ERR_BadVisParamType = 51, ERR_BadVisFieldType = 52, ERR_BadVisPropertyType = 53, ERR_BadVisIndexerReturn = 54, ERR_BadVisIndexerParam = 55, ERR_BadVisOpReturn = 56, ERR_BadVisOpParam = 57, ERR_BadVisDelegateReturn = 58, ERR_BadVisDelegateParam = 59, ERR_BadVisBaseClass = 60, ERR_BadVisBaseInterface = 61, ERR_EventNeedsBothAccessors = 65, ERR_EventNotDelegate = 66, WRN_UnreferencedEvent = 67, ERR_InterfaceEventInitializer = 68, //ERR_EventPropertyInInterface = 69, ERR_BadEventUsage = 70, ERR_ExplicitEventFieldImpl = 71, ERR_CantOverrideNonEvent = 72, ERR_AddRemoveMustHaveBody = 73, ERR_AbstractEventInitializer = 74, ERR_PossibleBadNegCast = 75, ERR_ReservedEnumerator = 76, ERR_AsMustHaveReferenceType = 77, WRN_LowercaseEllSuffix = 78, ERR_BadEventUsageNoField = 79, ERR_ConstraintOnlyAllowedOnGenericDecl = 80, ERR_TypeParamMustBeIdentifier = 81, ERR_MemberReserved = 82, ERR_DuplicateParamName = 100, ERR_DuplicateNameInNS = 101, ERR_DuplicateNameInClass = 102, ERR_NameNotInContext = 103, ERR_AmbigContext = 104, WRN_DuplicateUsing = 105, ERR_BadMemberFlag = 106, ERR_BadMemberProtection = 107, WRN_NewRequired = 108, WRN_NewNotRequired = 109, ERR_CircConstValue = 110, ERR_MemberAlreadyExists = 111, ERR_StaticNotVirtual = 112, ERR_OverrideNotNew = 113, WRN_NewOrOverrideExpected = 114, ERR_OverrideNotExpected = 115, ERR_NamespaceUnexpected = 116, ERR_NoSuchMember = 117, ERR_BadSKknown = 118, ERR_BadSKunknown = 119, ERR_ObjectRequired = 120, ERR_AmbigCall = 121, ERR_BadAccess = 122, ERR_MethDelegateMismatch = 123, ERR_RetObjectRequired = 126, ERR_RetNoObjectRequired = 127, ERR_LocalDuplicate = 128, ERR_AssgLvalueExpected = 131, ERR_StaticConstParam = 132, ERR_NotConstantExpression = 133, ERR_NotNullConstRefField = 134, // ERR_NameIllegallyOverrides = 135, // Not used in Roslyn anymore due to 'Single Meaning' relaxation changes ERR_LocalIllegallyOverrides = 136, ERR_BadUsingNamespace = 138, ERR_NoBreakOrCont = 139, ERR_DuplicateLabel = 140, ERR_NoConstructors = 143, ERR_NoNewAbstract = 144, ERR_ConstValueRequired = 145, ERR_CircularBase = 146, ERR_BadDelegateConstructor = 148, ERR_MethodNameExpected = 149, ERR_ConstantExpected = 150, // ERR_V6SwitchGoverningTypeValueExpected shares the same error code (CS0151) with ERR_IntegralTypeValueExpected in Dev10 compiler. // However ERR_IntegralTypeValueExpected is currently unused and hence being removed. If we need to generate this error in future // we can use error code CS0166. CS0166 was originally reserved for ERR_SwitchFallInto in Dev10, but was never used. ERR_V6SwitchGoverningTypeValueExpected = 151, ERR_DuplicateCaseLabel = 152, ERR_InvalidGotoCase = 153, ERR_PropertyLacksGet = 154, ERR_BadExceptionType = 155, ERR_BadEmptyThrow = 156, ERR_BadFinallyLeave = 157, ERR_LabelShadow = 158, ERR_LabelNotFound = 159, ERR_UnreachableCatch = 160, ERR_ReturnExpected = 161, WRN_UnreachableCode = 162, ERR_SwitchFallThrough = 163, WRN_UnreferencedLabel = 164, ERR_UseDefViolation = 165, //ERR_NoInvoke = 167, WRN_UnreferencedVar = 168, WRN_UnreferencedField = 169, ERR_UseDefViolationField = 170, ERR_UnassignedThis = 171, ERR_AmbigQM = 172, ERR_InvalidQM = 173, // Requires SymbolDistinguisher. ERR_NoBaseClass = 174, ERR_BaseIllegal = 175, ERR_ObjectProhibited = 176, ERR_ParamUnassigned = 177, ERR_InvalidArray = 178, ERR_ExternHasBody = 179, ERR_AbstractAndExtern = 180, ERR_BadAttributeParamType = 181, ERR_BadAttributeArgument = 182, WRN_IsAlwaysTrue = 183, WRN_IsAlwaysFalse = 184, ERR_LockNeedsReference = 185, ERR_NullNotValid = 186, ERR_UseDefViolationThis = 188, ERR_ArgsInvalid = 190, ERR_AssgReadonly = 191, ERR_RefReadonly = 192, ERR_PtrExpected = 193, ERR_PtrIndexSingle = 196, WRN_ByRefNonAgileField = 197, ERR_AssgReadonlyStatic = 198, ERR_RefReadonlyStatic = 199, ERR_AssgReadonlyProp = 200, ERR_IllegalStatement = 201, ERR_BadGetEnumerator = 202, ERR_TooManyLocals = 204, ERR_AbstractBaseCall = 205, ERR_RefProperty = 206, // WRN_OldWarning_UnsafeProp = 207, // This error code is unused. ERR_ManagedAddr = 208, ERR_BadFixedInitType = 209, ERR_FixedMustInit = 210, ERR_InvalidAddrOp = 211, ERR_FixedNeeded = 212, ERR_FixedNotNeeded = 213, ERR_UnsafeNeeded = 214, ERR_OpTFRetType = 215, ERR_OperatorNeedsMatch = 216, ERR_BadBoolOp = 217, ERR_MustHaveOpTF = 218, WRN_UnreferencedVarAssg = 219, ERR_CheckedOverflow = 220, ERR_ConstOutOfRangeChecked = 221, ERR_BadVarargs = 224, ERR_ParamsMustBeArray = 225, ERR_IllegalArglist = 226, ERR_IllegalUnsafe = 227, //ERR_NoAccessibleMember = 228, ERR_AmbigMember = 229, ERR_BadForeachDecl = 230, ERR_ParamsLast = 231, ERR_SizeofUnsafe = 233, ERR_DottedTypeNameNotFoundInNS = 234, ERR_FieldInitRefNonstatic = 236, ERR_SealedNonOverride = 238, ERR_CantOverrideSealed = 239, //ERR_NoDefaultArgs = 241, ERR_VoidError = 242, ERR_ConditionalOnOverride = 243, ERR_PointerInAsOrIs = 244, ERR_CallingFinalizeDeprecated = 245, //Dev10: ERR_CallingFinalizeDepracated ERR_SingleTypeNameNotFound = 246, ERR_NegativeStackAllocSize = 247, ERR_NegativeArraySize = 248, ERR_OverrideFinalizeDeprecated = 249, ERR_CallingBaseFinalizeDeprecated = 250, WRN_NegativeArrayIndex = 251, WRN_BadRefCompareLeft = 252, WRN_BadRefCompareRight = 253, ERR_BadCastInFixed = 254, ERR_StackallocInCatchFinally = 255, ERR_VarargsLast = 257, ERR_MissingPartial = 260, ERR_PartialTypeKindConflict = 261, ERR_PartialModifierConflict = 262, ERR_PartialMultipleBases = 263, ERR_PartialWrongTypeParams = 264, ERR_PartialWrongConstraints = 265, ERR_NoImplicitConvCast = 266, // Requires SymbolDistinguisher. ERR_PartialMisplaced = 267, ERR_ImportedCircularBase = 268, ERR_UseDefViolationOut = 269, ERR_ArraySizeInDeclaration = 270, ERR_InaccessibleGetter = 271, ERR_InaccessibleSetter = 272, ERR_InvalidPropertyAccessMod = 273, ERR_DuplicatePropertyAccessMods = 274, //ERR_PropertyAccessModInInterface = 275, ERR_AccessModMissingAccessor = 276, ERR_UnimplementedInterfaceAccessor = 277, WRN_PatternIsAmbiguous = 278, WRN_PatternNotPublicOrNotInstance = 279, WRN_PatternBadSignature = 280, ERR_FriendRefNotEqualToThis = 281, WRN_SequentialOnPartialClass = 282, ERR_BadConstType = 283, ERR_NoNewTyvar = 304, ERR_BadArity = 305, ERR_BadTypeArgument = 306, ERR_TypeArgsNotAllowed = 307, ERR_HasNoTypeVars = 308, ERR_NewConstraintNotSatisfied = 310, ERR_GenericConstraintNotSatisfiedRefType = 311, // Requires SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedNullableEnum = 312, // Uses (but doesn't require) SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedNullableInterface = 313, // Uses (but doesn't require) SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedTyVar = 314, // Requires SymbolDistinguisher. ERR_GenericConstraintNotSatisfiedValType = 315, // Requires SymbolDistinguisher. ERR_DuplicateGeneratedName = 316, // unused 317-399 ERR_GlobalSingleTypeNameNotFound = 400, ERR_NewBoundMustBeLast = 401, WRN_MainCantBeGeneric = 402, ERR_TypeVarCantBeNull = 403, ERR_AttributeCantBeGeneric = 404, ERR_DuplicateBound = 405, ERR_ClassBoundNotFirst = 406, ERR_BadRetType = 407, ERR_DuplicateConstraintClause = 409, //ERR_WrongSignature = 410, unused in Roslyn ERR_CantInferMethTypeArgs = 411, ERR_LocalSameNameAsTypeParam = 412, ERR_AsWithTypeVar = 413, WRN_UnreferencedFieldAssg = 414, ERR_BadIndexerNameAttr = 415, ERR_AttrArgWithTypeVars = 416, ERR_NewTyvarWithArgs = 417, ERR_AbstractSealedStatic = 418, WRN_AmbiguousXMLReference = 419, WRN_VolatileByRef = 420, // WRN_IncrSwitchObsolete = 422, // This error code is unused. ERR_ComImportWithImpl = 423, ERR_ComImportWithBase = 424, ERR_ImplBadConstraints = 425, ERR_DottedTypeNameNotFoundInAgg = 426, ERR_MethGrpToNonDel = 428, // WRN_UnreachableExpr = 429, // This error code is unused. ERR_BadExternAlias = 430, ERR_ColColWithTypeAlias = 431, ERR_AliasNotFound = 432, ERR_SameFullNameAggAgg = 433, ERR_SameFullNameNsAgg = 434, WRN_SameFullNameThisNsAgg = 435, WRN_SameFullNameThisAggAgg = 436, WRN_SameFullNameThisAggNs = 437, ERR_SameFullNameThisAggThisNs = 438, ERR_ExternAfterElements = 439, WRN_GlobalAliasDefn = 440, ERR_SealedStaticClass = 441, ERR_PrivateAbstractAccessor = 442, ERR_ValueExpected = 443, // WRN_UnexpectedPredefTypeLoc = 444, // This error code is unused. ERR_UnboxNotLValue = 445, ERR_AnonMethGrpInForEach = 446, //ERR_AttrOnTypeArg = 447, unused in Roslyn. The scenario for which this error exists should, and does generate a parse error. ERR_BadIncDecRetType = 448, ERR_TypeConstraintsMustBeUniqueAndFirst = 449, ERR_RefValBoundWithClass = 450, ERR_NewBoundWithVal = 451, ERR_RefConstraintNotSatisfied = 452, ERR_ValConstraintNotSatisfied = 453, ERR_CircularConstraint = 454, ERR_BaseConstraintConflict = 455, ERR_ConWithValCon = 456, ERR_AmbigUDConv = 457, WRN_AlwaysNull = 458, // ERR_AddrOnReadOnlyLocal = 459, // no longer an error ERR_OverrideWithConstraints = 460, ERR_AmbigOverride = 462, ERR_DecConstError = 463, WRN_CmpAlwaysFalse = 464, WRN_FinalizeMethod = 465, ERR_ExplicitImplParams = 466, // WRN_AmbigLookupMeth = 467, //no longer issued in Roslyn //ERR_SameFullNameThisAggThisAgg = 468, no longer used in Roslyn WRN_GotoCaseShouldConvert = 469, ERR_MethodImplementingAccessor = 470, //ERR_TypeArgsNotAllowedAmbig = 471, no longer issued in Roslyn WRN_NubExprIsConstBool = 472, WRN_ExplicitImplCollision = 473, // unused 474-499 ERR_AbstractHasBody = 500, ERR_ConcreteMissingBody = 501, ERR_AbstractAndSealed = 502, ERR_AbstractNotVirtual = 503, ERR_StaticConstant = 504, ERR_CantOverrideNonFunction = 505, ERR_CantOverrideNonVirtual = 506, ERR_CantChangeAccessOnOverride = 507, ERR_CantChangeReturnTypeOnOverride = 508, ERR_CantDeriveFromSealedType = 509, ERR_AbstractInConcreteClass = 513, ERR_StaticConstructorWithExplicitConstructorCall = 514, ERR_StaticConstructorWithAccessModifiers = 515, ERR_RecursiveConstructorCall = 516, ERR_ObjectCallingBaseConstructor = 517, ERR_PredefinedTypeNotFound = 518, //ERR_PredefinedTypeBadType = 520, ERR_StructWithBaseConstructorCall = 522, ERR_StructLayoutCycle = 523, //ERR_InterfacesCannotContainTypes = 524, ERR_InterfacesCantContainFields = 525, ERR_InterfacesCantContainConstructors = 526, ERR_NonInterfaceInInterfaceList = 527, ERR_DuplicateInterfaceInBaseList = 528, ERR_CycleInInterfaceInheritance = 529, //ERR_InterfaceMemberHasBody = 531, ERR_HidingAbstractMethod = 533, ERR_UnimplementedAbstractMethod = 534, ERR_UnimplementedInterfaceMember = 535, ERR_ObjectCantHaveBases = 537, ERR_ExplicitInterfaceImplementationNotInterface = 538, ERR_InterfaceMemberNotFound = 539, ERR_ClassDoesntImplementInterface = 540, ERR_ExplicitInterfaceImplementationInNonClassOrStruct = 541, ERR_MemberNameSameAsType = 542, ERR_EnumeratorOverflow = 543, ERR_CantOverrideNonProperty = 544, ERR_NoGetToOverride = 545, ERR_NoSetToOverride = 546, ERR_PropertyCantHaveVoidType = 547, ERR_PropertyWithNoAccessors = 548, ERR_NewVirtualInSealed = 549, ERR_ExplicitPropertyAddingAccessor = 550, ERR_ExplicitPropertyMissingAccessor = 551, ERR_ConversionWithInterface = 552, ERR_ConversionWithBase = 553, ERR_ConversionWithDerived = 554, ERR_IdentityConversion = 555, ERR_ConversionNotInvolvingContainedType = 556, ERR_DuplicateConversionInClass = 557, ERR_OperatorsMustBeStatic = 558, ERR_BadIncDecSignature = 559, ERR_BadUnaryOperatorSignature = 562, ERR_BadBinaryOperatorSignature = 563, ERR_BadShiftOperatorSignature = 564, ERR_InterfacesCantContainConversionOrEqualityOperators = 567, //ERR_StructsCantContainDefaultConstructor = 568, ERR_CantOverrideBogusMethod = 569, ERR_BindToBogus = 570, ERR_CantCallSpecialMethod = 571, ERR_BadTypeReference = 572, //ERR_FieldInitializerInStruct = 573, ERR_BadDestructorName = 574, ERR_OnlyClassesCanContainDestructors = 575, ERR_ConflictAliasAndMember = 576, ERR_ConditionalOnSpecialMethod = 577, ERR_ConditionalMustReturnVoid = 578, ERR_DuplicateAttribute = 579, ERR_ConditionalOnInterfaceMethod = 582, //ERR_ICE_Culprit = 583, No ICE in Roslyn. All of these are unused //ERR_ICE_Symbol = 584, //ERR_ICE_Node = 585, //ERR_ICE_File = 586, //ERR_ICE_Stage = 587, //ERR_ICE_Lexer = 588, //ERR_ICE_Parser = 589, ERR_OperatorCantReturnVoid = 590, ERR_InvalidAttributeArgument = 591, ERR_AttributeOnBadSymbolType = 592, ERR_FloatOverflow = 594, ERR_InvalidReal = 595, ERR_ComImportWithoutUuidAttribute = 596, ERR_InvalidNamedArgument = 599, ERR_DllImportOnInvalidMethod = 601, // WRN_FeatureDeprecated = 602, // This error code is unused. // ERR_NameAttributeOnOverride = 609, // removed in Roslyn ERR_FieldCantBeRefAny = 610, ERR_ArrayElementCantBeRefAny = 611, WRN_DeprecatedSymbol = 612, ERR_NotAnAttributeClass = 616, ERR_BadNamedAttributeArgument = 617, WRN_DeprecatedSymbolStr = 618, ERR_DeprecatedSymbolStr = 619, ERR_IndexerCantHaveVoidType = 620, ERR_VirtualPrivate = 621, ERR_ArrayInitToNonArrayType = 622, ERR_ArrayInitInBadPlace = 623, ERR_MissingStructOffset = 625, WRN_ExternMethodNoImplementation = 626, WRN_ProtectedInSealed = 628, ERR_InterfaceImplementedByConditional = 629, ERR_InterfaceImplementedImplicitlyByVariadic = 630, ERR_IllegalRefParam = 631, ERR_BadArgumentToAttribute = 633, //ERR_MissingComTypeOrMarshaller = 635, ERR_StructOffsetOnBadStruct = 636, ERR_StructOffsetOnBadField = 637, ERR_AttributeUsageOnNonAttributeClass = 641, WRN_PossibleMistakenNullStatement = 642, ERR_DuplicateNamedAttributeArgument = 643, ERR_DeriveFromEnumOrValueType = 644, //ERR_IdentifierTooLong = 645, //not used in Roslyn. See ERR_MetadataNameTooLong ERR_DefaultMemberOnIndexedType = 646, //ERR_CustomAttributeError = 647, ERR_BogusType = 648, WRN_UnassignedInternalField = 649, ERR_CStyleArray = 650, WRN_VacuousIntegralComp = 652, ERR_AbstractAttributeClass = 653, ERR_BadNamedAttributeArgumentType = 655, ERR_MissingPredefinedMember = 656, WRN_AttributeLocationOnBadDeclaration = 657, WRN_InvalidAttributeLocation = 658, WRN_EqualsWithoutGetHashCode = 659, WRN_EqualityOpWithoutEquals = 660, WRN_EqualityOpWithoutGetHashCode = 661, ERR_OutAttrOnRefParam = 662, ERR_OverloadRefKind = 663, ERR_LiteralDoubleCast = 664, WRN_IncorrectBooleanAssg = 665, ERR_ProtectedInStruct = 666, //ERR_FeatureDeprecated = 667, ERR_InconsistentIndexerNames = 668, // Named 'ERR_InconsistantIndexerNames' in native compiler ERR_ComImportWithUserCtor = 669, ERR_FieldCantHaveVoidType = 670, WRN_NonObsoleteOverridingObsolete = 672, ERR_SystemVoid = 673, ERR_ExplicitParamArray = 674, WRN_BitwiseOrSignExtend = 675, ERR_VolatileStruct = 677, ERR_VolatileAndReadonly = 678, // WRN_OldWarning_ProtectedInternal = 679, // This error code is unused. // WRN_OldWarning_AccessibleReadonly = 680, // This error code is unused. ERR_AbstractField = 681, ERR_BogusExplicitImpl = 682, ERR_ExplicitMethodImplAccessor = 683, WRN_CoClassWithoutComImport = 684, ERR_ConditionalWithOutParam = 685, ERR_AccessorImplementingMethod = 686, ERR_AliasQualAsExpression = 687, ERR_DerivingFromATyVar = 689, //FTL_MalformedMetadata = 690, ERR_DuplicateTypeParameter = 692, WRN_TypeParameterSameAsOuterTypeParameter = 693, ERR_TypeVariableSameAsParent = 694, ERR_UnifyingInterfaceInstantiations = 695, ERR_GenericDerivingFromAttribute = 698, ERR_TyVarNotFoundInConstraint = 699, ERR_BadBoundType = 701, ERR_SpecialTypeAsBound = 702, ERR_BadVisBound = 703, ERR_LookupInTypeVariable = 704, ERR_BadConstraintType = 706, ERR_InstanceMemberInStaticClass = 708, ERR_StaticBaseClass = 709, ERR_ConstructorInStaticClass = 710, ERR_DestructorInStaticClass = 711, ERR_InstantiatingStaticClass = 712, ERR_StaticDerivedFromNonObject = 713, ERR_StaticClassInterfaceImpl = 714, ERR_OperatorInStaticClass = 715, ERR_ConvertToStaticClass = 716, ERR_ConstraintIsStaticClass = 717, ERR_GenericArgIsStaticClass = 718, ERR_ArrayOfStaticClass = 719, ERR_IndexerInStaticClass = 720, ERR_ParameterIsStaticClass = 721, ERR_ReturnTypeIsStaticClass = 722, ERR_VarDeclIsStaticClass = 723, ERR_BadEmptyThrowInFinally = 724, //ERR_InvalidDecl = 725, ERR_InvalidSpecifier = 726, //ERR_InvalidSpecifierUnk = 727, WRN_AssignmentToLockOrDispose = 728, ERR_ForwardedTypeInThisAssembly = 729, ERR_ForwardedTypeIsNested = 730, ERR_CycleInTypeForwarder = 731, //ERR_FwdedGeneric = 733, ERR_AssemblyNameOnNonModule = 734, ERR_InvalidFwdType = 735, ERR_CloseUnimplementedInterfaceMemberStatic = 736, ERR_CloseUnimplementedInterfaceMemberNotPublic = 737, ERR_CloseUnimplementedInterfaceMemberWrongReturnType = 738, ERR_DuplicateTypeForwarder = 739, ERR_ExpectedSelectOrGroup = 742, ERR_ExpectedContextualKeywordOn = 743, ERR_ExpectedContextualKeywordEquals = 744, ERR_ExpectedContextualKeywordBy = 745, ERR_InvalidAnonymousTypeMemberDeclarator = 746, ERR_InvalidInitializerElementInitializer = 747, ERR_InconsistentLambdaParameterUsage = 748, ERR_PartialMethodInvalidModifier = 750, ERR_PartialMethodOnlyInPartialClass = 751, // ERR_PartialMethodCannotHaveOutParameters = 752, Removed as part of 'extended partial methods' feature // ERR_PartialMethodOnlyMethods = 753, Removed as it is subsumed by ERR_PartialMisplaced ERR_PartialMethodNotExplicit = 754, ERR_PartialMethodExtensionDifference = 755, ERR_PartialMethodOnlyOneLatent = 756, ERR_PartialMethodOnlyOneActual = 757, ERR_PartialMethodParamsDifference = 758, ERR_PartialMethodMustHaveLatent = 759, ERR_PartialMethodInconsistentConstraints = 761, ERR_PartialMethodToDelegate = 762, ERR_PartialMethodStaticDifference = 763, ERR_PartialMethodUnsafeDifference = 764, ERR_PartialMethodInExpressionTree = 765, // ERR_PartialMethodMustReturnVoid = 766, Removed as part of 'extended partial methods' feature ERR_ExplicitImplCollisionOnRefOut = 767, ERR_IndirectRecursiveConstructorCall = 768, // unused 769-799 //ERR_NoEmptyArrayRanges = 800, //ERR_IntegerSpecifierOnOneDimArrays = 801, //ERR_IntegerSpecifierMustBePositive = 802, //ERR_ArrayRangeDimensionsMustMatch = 803, //ERR_ArrayRangeDimensionsWrong = 804, //ERR_IntegerSpecifierValidOnlyOnArrays = 805, //ERR_ArrayRangeSpecifierValidOnlyOnArrays = 806, //ERR_UseAdditionalSquareBrackets = 807, //ERR_DotDotNotAssociative = 808, WRN_ObsoleteOverridingNonObsolete = 809, WRN_DebugFullNameTooLong = 811, // Dev11 name: ERR_DebugFullNameTooLong ERR_ImplicitlyTypedVariableAssignedBadValue = 815, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedBadValue ERR_ImplicitlyTypedVariableWithNoInitializer = 818, // Dev10 name: ERR_ImplicitlyTypedLocalWithNoInitializer ERR_ImplicitlyTypedVariableMultipleDeclarator = 819, // Dev10 name: ERR_ImplicitlyTypedLocalMultipleDeclarator ERR_ImplicitlyTypedVariableAssignedArrayInitializer = 820, // Dev10 name: ERR_ImplicitlyTypedLocalAssignedArrayInitializer ERR_ImplicitlyTypedLocalCannotBeFixed = 821, ERR_ImplicitlyTypedVariableCannotBeConst = 822, // Dev10 name: ERR_ImplicitlyTypedLocalCannotBeConst WRN_ExternCtorNoImplementation = 824, ERR_TypeVarNotFound = 825, ERR_ImplicitlyTypedArrayNoBestType = 826, ERR_AnonymousTypePropertyAssignedBadValue = 828, ERR_ExpressionTreeContainsBaseAccess = 831, ERR_ExpressionTreeContainsAssignment = 832, ERR_AnonymousTypeDuplicatePropertyName = 833, ERR_StatementLambdaToExpressionTree = 834, ERR_ExpressionTreeMustHaveDelegate = 835, ERR_AnonymousTypeNotAvailable = 836, ERR_LambdaInIsAs = 837, ERR_ExpressionTreeContainsMultiDimensionalArrayInitializer = 838, ERR_MissingArgument = 839, //ERR_AutoPropertiesMustHaveBothAccessors = 840, ERR_VariableUsedBeforeDeclaration = 841, //ERR_ExplicitLayoutAndAutoImplementedProperty = 842, ERR_UnassignedThisAutoProperty = 843, ERR_VariableUsedBeforeDeclarationAndHidesField = 844, ERR_ExpressionTreeContainsBadCoalesce = 845, ERR_ArrayInitializerExpected = 846, ERR_ArrayInitializerIncorrectLength = 847, // ERR_OverloadRefOutCtor = 851, Replaced By ERR_OverloadRefKind ERR_ExpressionTreeContainsNamedArgument = 853, ERR_ExpressionTreeContainsOptionalArgument = 854, ERR_ExpressionTreeContainsIndexedProperty = 855, ERR_IndexedPropertyRequiresParams = 856, ERR_IndexedPropertyMustHaveAllOptionalParams = 857, //ERR_FusionConfigFileNameTooLong = 858, unused in Roslyn. We give ERR_CantReadConfigFile now. // unused 859-1000 ERR_IdentifierExpected = 1001, ERR_SemicolonExpected = 1002, ERR_SyntaxError = 1003, ERR_DuplicateModifier = 1004, ERR_DuplicateAccessor = 1007, ERR_IntegralTypeExpected = 1008, ERR_IllegalEscape = 1009, ERR_NewlineInConst = 1010, ERR_EmptyCharConst = 1011, ERR_TooManyCharsInConst = 1012, ERR_InvalidNumber = 1013, ERR_GetOrSetExpected = 1014, ERR_ClassTypeExpected = 1015, ERR_NamedArgumentExpected = 1016, ERR_TooManyCatches = 1017, ERR_ThisOrBaseExpected = 1018, ERR_OvlUnaryOperatorExpected = 1019, ERR_OvlBinaryOperatorExpected = 1020, ERR_IntOverflow = 1021, ERR_EOFExpected = 1022, ERR_BadEmbeddedStmt = 1023, ERR_PPDirectiveExpected = 1024, ERR_EndOfPPLineExpected = 1025, ERR_CloseParenExpected = 1026, ERR_EndifDirectiveExpected = 1027, ERR_UnexpectedDirective = 1028, ERR_ErrorDirective = 1029, WRN_WarningDirective = 1030, ERR_TypeExpected = 1031, ERR_PPDefFollowsToken = 1032, //ERR_TooManyLines = 1033, unused in Roslyn. //ERR_LineTooLong = 1034, unused in Roslyn. ERR_OpenEndedComment = 1035, ERR_OvlOperatorExpected = 1037, ERR_EndRegionDirectiveExpected = 1038, ERR_UnterminatedStringLit = 1039, ERR_BadDirectivePlacement = 1040, ERR_IdentifierExpectedKW = 1041, ERR_SemiOrLBraceExpected = 1043, ERR_MultiTypeInDeclaration = 1044, ERR_AddOrRemoveExpected = 1055, ERR_UnexpectedCharacter = 1056, ERR_ProtectedInStatic = 1057, WRN_UnreachableGeneralCatch = 1058, ERR_IncrementLvalueExpected = 1059, // WRN_UninitializedField = 1060, // unused in Roslyn. ERR_NoSuchMemberOrExtension = 1061, WRN_DeprecatedCollectionInitAddStr = 1062, ERR_DeprecatedCollectionInitAddStr = 1063, WRN_DeprecatedCollectionInitAdd = 1064, ERR_DefaultValueNotAllowed = 1065, WRN_DefaultValueForUnconsumedLocation = 1066, ERR_PartialWrongTypeParamsVariance = 1067, ERR_GlobalSingleTypeNameNotFoundFwd = 1068, ERR_DottedTypeNameNotFoundInNSFwd = 1069, ERR_SingleTypeNameNotFoundFwd = 1070, //ERR_NoSuchMemberOnNoPIAType = 1071, //EE WRN_IdentifierOrNumericLiteralExpected = 1072, ERR_UnexpectedToken = 1073, // unused 1074-1098 // ERR_EOLExpected = 1099, // EE // ERR_NotSupportedinEE = 1100, // EE ERR_BadThisParam = 1100, // ERR_BadRefWithThis = 1101, replaced by ERR_BadParameterModifiers // ERR_BadOutWithThis = 1102, replaced by ERR_BadParameterModifiers ERR_BadTypeforThis = 1103, ERR_BadParamModThis = 1104, ERR_BadExtensionMeth = 1105, ERR_BadExtensionAgg = 1106, ERR_DupParamMod = 1107, // ERR_MultiParamMod = 1108, replaced by ERR_BadParameterModifiers ERR_ExtensionMethodsDecl = 1109, ERR_ExtensionAttrNotFound = 1110, //ERR_ExtensionTypeParam = 1111, ERR_ExplicitExtension = 1112, ERR_ValueTypeExtDelegate = 1113, // unused 1114-1199 // Below five error codes are unused. // WRN_FeatureDeprecated2 = 1200, // WRN_FeatureDeprecated3 = 1201, // WRN_FeatureDeprecated4 = 1202, // WRN_FeatureDeprecated5 = 1203, // WRN_OldWarning_FeatureDefaultDeprecated = 1204, // unused 1205-1500 ERR_BadArgCount = 1501, //ERR_BadArgTypes = 1502, ERR_BadArgType = 1503, ERR_NoSourceFile = 1504, ERR_CantRefResource = 1507, ERR_ResourceNotUnique = 1508, ERR_ImportNonAssembly = 1509, ERR_RefLvalueExpected = 1510, ERR_BaseInStaticMeth = 1511, ERR_BaseInBadContext = 1512, ERR_RbraceExpected = 1513, ERR_LbraceExpected = 1514, ERR_InExpected = 1515, ERR_InvalidPreprocExpr = 1517, //ERR_BadTokenInType = 1518, unused in Roslyn ERR_InvalidMemberDecl = 1519, ERR_MemberNeedsType = 1520, ERR_BadBaseType = 1521, WRN_EmptySwitch = 1522, ERR_ExpectedEndTry = 1524, ERR_InvalidExprTerm = 1525, ERR_BadNewExpr = 1526, ERR_NoNamespacePrivate = 1527, ERR_BadVarDecl = 1528, ERR_UsingAfterElements = 1529, //ERR_NoNewOnNamespaceElement = 1530, EDMAURER we now give BadMemberFlag which is only a little less specific than this. //ERR_DontUseInvoke = 1533, ERR_BadBinOpArgs = 1534, ERR_BadUnOpArgs = 1535, ERR_NoVoidParameter = 1536, ERR_DuplicateAlias = 1537, ERR_BadProtectedAccess = 1540, //ERR_CantIncludeDirectory = 1541, ERR_AddModuleAssembly = 1542, ERR_BindToBogusProp2 = 1545, ERR_BindToBogusProp1 = 1546, ERR_NoVoidHere = 1547, //ERR_CryptoFailed = 1548, //ERR_CryptoNotFound = 1549, ERR_IndexerNeedsParam = 1551, ERR_BadArraySyntax = 1552, ERR_BadOperatorSyntax = 1553, //ERR_BadOperatorSyntax2 = 1554, Not used in Roslyn. ERR_MainClassNotFound = 1555, ERR_MainClassNotClass = 1556, //ERR_MainClassWrongFile = 1557, Not used in Roslyn. This was used only when compiling and producing two outputs. ERR_NoMainInClass = 1558, //ERR_MainClassIsImport = 1559, Not used in Roslyn. Scenario occurs so infrequently that it is not worth re-implementing. //ERR_FileNameTooLong = 1560, //ERR_OutputFileNameTooLong = 1561, Not used in Roslyn. We report a more generic error that doesn't mention "output file" but is fine. ERR_OutputNeedsName = 1562, //ERR_OutputNeedsInput = 1563, ERR_CantHaveWin32ResAndManifest = 1564, ERR_CantHaveWin32ResAndIcon = 1565, ERR_CantReadResource = 1566, //ERR_AutoResGen = 1567, ERR_DocFileGen = 1569, WRN_XMLParseError = 1570, WRN_DuplicateParamTag = 1571, WRN_UnmatchedParamTag = 1572, WRN_MissingParamTag = 1573, WRN_BadXMLRef = 1574, ERR_BadStackAllocExpr = 1575, ERR_InvalidLineNumber = 1576, //ERR_ALinkFailed = 1577, No alink usage in Roslyn ERR_MissingPPFile = 1578, ERR_ForEachMissingMember = 1579, WRN_BadXMLRefParamType = 1580, WRN_BadXMLRefReturnType = 1581, ERR_BadWin32Res = 1583, WRN_BadXMLRefSyntax = 1584, ERR_BadModifierLocation = 1585, ERR_MissingArraySize = 1586, WRN_UnprocessedXMLComment = 1587, //ERR_CantGetCORSystemDir = 1588, WRN_FailedInclude = 1589, WRN_InvalidInclude = 1590, WRN_MissingXMLComment = 1591, WRN_XMLParseIncludeError = 1592, ERR_BadDelArgCount = 1593, //ERR_BadDelArgTypes = 1594, // WRN_OldWarning_MultipleTypeDefs = 1595, // This error code is unused. // WRN_OldWarning_DocFileGenAndIncr = 1596, // This error code is unused. ERR_UnexpectedSemicolon = 1597, // WRN_XMLParserNotFound = 1598, // No longer used (though, conceivably, we could report it if Linq to Xml is missing at compile time). ERR_MethodReturnCantBeRefAny = 1599, ERR_CompileCancelled = 1600, ERR_MethodArgCantBeRefAny = 1601, ERR_AssgReadonlyLocal = 1604, ERR_RefReadonlyLocal = 1605, //ERR_ALinkCloseFailed = 1606, WRN_ALinkWarn = 1607, ERR_CantUseRequiredAttribute = 1608, ERR_NoModifiersOnAccessor = 1609, // WRN_DeleteAutoResFailed = 1610, // Unused. ERR_ParamsCantBeWithModifier = 1611, ERR_ReturnNotLValue = 1612, ERR_MissingCoClass = 1613, ERR_AmbiguousAttribute = 1614, ERR_BadArgExtraRef = 1615, WRN_CmdOptionConflictsSource = 1616, ERR_BadCompatMode = 1617, ERR_DelegateOnConditional = 1618, ERR_CantMakeTempFile = 1619, //changed to now accept only one argument ERR_BadArgRef = 1620, ERR_YieldInAnonMeth = 1621, ERR_ReturnInIterator = 1622, ERR_BadIteratorArgType = 1623, ERR_BadIteratorReturn = 1624, ERR_BadYieldInFinally = 1625, ERR_BadYieldInTryOfCatch = 1626, ERR_EmptyYield = 1627, ERR_AnonDelegateCantUse = 1628, ERR_IllegalInnerUnsafe = 1629, //ERR_BadWatsonMode = 1630, ERR_BadYieldInCatch = 1631, ERR_BadDelegateLeave = 1632, WRN_IllegalPragma = 1633, WRN_IllegalPPWarning = 1634, WRN_BadRestoreNumber = 1635, ERR_VarargsIterator = 1636, ERR_UnsafeIteratorArgType = 1637, //ERR_ReservedIdentifier = 1638, ERR_BadCoClassSig = 1639, ERR_MultipleIEnumOfT = 1640, ERR_FixedDimsRequired = 1641, ERR_FixedNotInStruct = 1642, ERR_AnonymousReturnExpected = 1643, //ERR_NonECMAFeature = 1644, WRN_NonECMAFeature = 1645, ERR_ExpectedVerbatimLiteral = 1646, //FTL_StackOverflow = 1647, ERR_AssgReadonly2 = 1648, ERR_RefReadonly2 = 1649, ERR_AssgReadonlyStatic2 = 1650, ERR_RefReadonlyStatic2 = 1651, ERR_AssgReadonlyLocal2Cause = 1654, ERR_RefReadonlyLocal2Cause = 1655, ERR_AssgReadonlyLocalCause = 1656, ERR_RefReadonlyLocalCause = 1657, WRN_ErrorOverride = 1658, // WRN_OldWarning_ReservedIdentifier = 1659, // This error code is unused. ERR_AnonMethToNonDel = 1660, ERR_CantConvAnonMethParams = 1661, ERR_CantConvAnonMethReturns = 1662, ERR_IllegalFixedType = 1663, ERR_FixedOverflow = 1664, ERR_InvalidFixedArraySize = 1665, ERR_FixedBufferNotFixed = 1666, ERR_AttributeNotOnAccessor = 1667, WRN_InvalidSearchPathDir = 1668, ERR_IllegalVarArgs = 1669, ERR_IllegalParams = 1670, ERR_BadModifiersOnNamespace = 1671, ERR_BadPlatformType = 1672, ERR_ThisStructNotInAnonMeth = 1673, ERR_NoConvToIDisp = 1674, // ERR_InvalidGenericEnum = 1675, replaced with 7002 ERR_BadParamRef = 1676, ERR_BadParamExtraRef = 1677, ERR_BadParamType = 1678, // Requires SymbolDistinguisher. ERR_BadExternIdentifier = 1679, ERR_AliasMissingFile = 1680, ERR_GlobalExternAlias = 1681, // WRN_MissingTypeNested = 1682, // unused in Roslyn. // In Roslyn, we generate errors ERR_MissingTypeInSource and ERR_MissingTypeInAssembly instead of warnings WRN_MissingTypeInSource and WRN_MissingTypeInAssembly respectively. // WRN_MissingTypeInSource = 1683, // WRN_MissingTypeInAssembly = 1684, WRN_MultiplePredefTypes = 1685, ERR_LocalCantBeFixedAndHoisted = 1686, WRN_TooManyLinesForDebugger = 1687, ERR_CantConvAnonMethNoParams = 1688, ERR_ConditionalOnNonAttributeClass = 1689, WRN_CallOnNonAgileField = 1690, // WRN_BadWarningNumber = 1691, // we no longer generate this warning for an unrecognized warning ID specified as an argument to /nowarn or /warnaserror. WRN_InvalidNumber = 1692, // WRN_FileNameTooLong = 1694, //unused. WRN_IllegalPPChecksum = 1695, WRN_EndOfPPLineExpected = 1696, WRN_ConflictingChecksum = 1697, // WRN_AssumedMatchThis = 1698, // This error code is unused. // WRN_UseSwitchInsteadOfAttribute = 1699, // This error code is unused. WRN_InvalidAssemblyName = 1700, WRN_UnifyReferenceMajMin = 1701, WRN_UnifyReferenceBldRev = 1702, ERR_DuplicateImport = 1703, ERR_DuplicateImportSimple = 1704, ERR_AssemblyMatchBadVersion = 1705, //ERR_AnonMethNotAllowed = 1706, Unused in Roslyn. Previously given when a lambda was supplied as an attribute argument. // WRN_DelegateNewMethBind = 1707, // This error code is unused. ERR_FixedNeedsLvalue = 1708, // WRN_EmptyFileName = 1709, // This error code is unused. WRN_DuplicateTypeParamTag = 1710, WRN_UnmatchedTypeParamTag = 1711, WRN_MissingTypeParamTag = 1712, //FTL_TypeNameBuilderError = 1713, //ERR_ImportBadBase = 1714, // This error code is unused and replaced with ERR_NoTypeDef ERR_CantChangeTypeOnOverride = 1715, ERR_DoNotUseFixedBufferAttr = 1716, WRN_AssignmentToSelf = 1717, WRN_ComparisonToSelf = 1718, ERR_CantOpenWin32Res = 1719, WRN_DotOnDefault = 1720, ERR_NoMultipleInheritance = 1721, ERR_BaseClassMustBeFirst = 1722, WRN_BadXMLRefTypeVar = 1723, //ERR_InvalidDefaultCharSetValue = 1724, Not used in Roslyn. ERR_FriendAssemblyBadArgs = 1725, ERR_FriendAssemblySNReq = 1726, //ERR_WatsonSendNotOptedIn = 1727, We're not doing any custom Watson processing in Roslyn. In modern OSs, Watson behavior is configured with machine policy settings. ERR_DelegateOnNullable = 1728, ERR_BadCtorArgCount = 1729, ERR_GlobalAttributesNotFirst = 1730, //ERR_CantConvAnonMethReturnsNoDelegate = 1731, Not used in Roslyn. When there is no delegate, we reuse the message that contains a substitution string for the delegate type. //ERR_ParameterExpected = 1732, Not used in Roslyn. ERR_ExpressionExpected = 1733, WRN_UnmatchedParamRefTag = 1734, WRN_UnmatchedTypeParamRefTag = 1735, ERR_DefaultValueMustBeConstant = 1736, ERR_DefaultValueBeforeRequiredValue = 1737, ERR_NamedArgumentSpecificationBeforeFixedArgument = 1738, ERR_BadNamedArgument = 1739, ERR_DuplicateNamedArgument = 1740, ERR_RefOutDefaultValue = 1741, ERR_NamedArgumentForArray = 1742, ERR_DefaultValueForExtensionParameter = 1743, ERR_NamedArgumentUsedInPositional = 1744, ERR_DefaultValueUsedWithAttributes = 1745, ERR_BadNamedArgumentForDelegateInvoke = 1746, ERR_NoPIAAssemblyMissingAttribute = 1747, ERR_NoCanonicalView = 1748, //ERR_TypeNotFoundForNoPIA = 1749, ERR_NoConversionForDefaultParam = 1750, ERR_DefaultValueForParamsParameter = 1751, ERR_NewCoClassOnLink = 1752, ERR_NoPIANestedType = 1754, //ERR_InvalidTypeIdentifierConstructor = 1755, ERR_InteropTypeMissingAttribute = 1756, ERR_InteropStructContainsMethods = 1757, ERR_InteropTypesWithSameNameAndGuid = 1758, ERR_NoPIAAssemblyMissingAttributes = 1759, ERR_AssemblySpecifiedForLinkAndRef = 1760, ERR_LocalTypeNameClash = 1761, WRN_ReferencedAssemblyReferencesLinkedPIA = 1762, ERR_NotNullRefDefaultParameter = 1763, ERR_FixedLocalInLambda = 1764, // WRN_TypeNotFoundForNoPIAWarning = 1765, // This error code is unused. ERR_MissingMethodOnSourceInterface = 1766, ERR_MissingSourceInterface = 1767, ERR_GenericsUsedInNoPIAType = 1768, ERR_GenericsUsedAcrossAssemblies = 1769, ERR_NoConversionForNubDefaultParam = 1770, //ERR_MemberWithGenericsUsedAcrossAssemblies = 1771, //ERR_GenericsUsedInBaseTypeAcrossAssemblies = 1772, ERR_InvalidSubsystemVersion = 1773, ERR_InteropMethodWithBody = 1774, // unused 1775-1899 ERR_BadWarningLevel = 1900, ERR_BadDebugType = 1902, //ERR_UnknownTestSwitch = 1903, ERR_BadResourceVis = 1906, ERR_DefaultValueTypeMustMatch = 1908, //ERR_DefaultValueBadParamType = 1909, // Replaced by ERR_DefaultValueBadValueType in Roslyn. ERR_DefaultValueBadValueType = 1910, ERR_MemberAlreadyInitialized = 1912, ERR_MemberCannotBeInitialized = 1913, ERR_StaticMemberInObjectInitializer = 1914, ERR_ReadonlyValueTypeInObjectInitializer = 1917, ERR_ValueTypePropertyInObjectInitializer = 1918, ERR_UnsafeTypeInObjectCreation = 1919, ERR_EmptyElementInitializer = 1920, ERR_InitializerAddHasWrongSignature = 1921, ERR_CollectionInitRequiresIEnumerable = 1922, //ERR_InvalidCollectionInitializerType = 1925, unused in Roslyn. Occurs so infrequently in real usage that it is not worth reimplementing. ERR_CantOpenWin32Manifest = 1926, WRN_CantHaveManifestForModule = 1927, //ERR_BadExtensionArgTypes = 1928, unused in Roslyn (replaced by ERR_BadInstanceArgType) ERR_BadInstanceArgType = 1929, ERR_QueryDuplicateRangeVariable = 1930, ERR_QueryRangeVariableOverrides = 1931, ERR_QueryRangeVariableAssignedBadValue = 1932, //ERR_QueryNotAllowed = 1933, unused in Roslyn. This specific message is not necessary for correctness and adds little. ERR_QueryNoProviderCastable = 1934, ERR_QueryNoProviderStandard = 1935, ERR_QueryNoProvider = 1936, ERR_QueryOuterKey = 1937, ERR_QueryInnerKey = 1938, ERR_QueryOutRefRangeVariable = 1939, ERR_QueryMultipleProviders = 1940, ERR_QueryTypeInferenceFailedMulti = 1941, ERR_QueryTypeInferenceFailed = 1942, ERR_QueryTypeInferenceFailedSelectMany = 1943, ERR_ExpressionTreeContainsPointerOp = 1944, ERR_ExpressionTreeContainsAnonymousMethod = 1945, ERR_AnonymousMethodToExpressionTree = 1946, ERR_QueryRangeVariableReadOnly = 1947, ERR_QueryRangeVariableSameAsTypeParam = 1948, ERR_TypeVarNotFoundRangeVariable = 1949, ERR_BadArgTypesForCollectionAdd = 1950, ERR_ByRefParameterInExpressionTree = 1951, ERR_VarArgsInExpressionTree = 1952, // ERR_MemGroupInExpressionTree = 1953, unused in Roslyn (replaced by ERR_LambdaInIsAs) ERR_InitializerAddHasParamModifiers = 1954, ERR_NonInvocableMemberCalled = 1955, WRN_MultipleRuntimeImplementationMatches = 1956, WRN_MultipleRuntimeOverrideMatches = 1957, ERR_ObjectOrCollectionInitializerWithDelegateCreation = 1958, ERR_InvalidConstantDeclarationType = 1959, ERR_IllegalVarianceSyntax = 1960, ERR_UnexpectedVariance = 1961, ERR_BadDynamicTypeof = 1962, ERR_ExpressionTreeContainsDynamicOperation = 1963, ERR_BadDynamicConversion = 1964, ERR_DeriveFromDynamic = 1965, ERR_DeriveFromConstructedDynamic = 1966, ERR_DynamicTypeAsBound = 1967, ERR_ConstructedDynamicTypeAsBound = 1968, ERR_DynamicRequiredTypesMissing = 1969, ERR_ExplicitDynamicAttr = 1970, ERR_NoDynamicPhantomOnBase = 1971, ERR_NoDynamicPhantomOnBaseIndexer = 1972, ERR_BadArgTypeDynamicExtension = 1973, WRN_DynamicDispatchToConditionalMethod = 1974, ERR_NoDynamicPhantomOnBaseCtor = 1975, ERR_BadDynamicMethodArgMemgrp = 1976, ERR_BadDynamicMethodArgLambda = 1977, ERR_BadDynamicMethodArg = 1978, ERR_BadDynamicQuery = 1979, ERR_DynamicAttributeMissing = 1980, WRN_IsDynamicIsConfusing = 1981, //ERR_DynamicNotAllowedInAttribute = 1982, // Replaced by ERR_BadAttributeParamType in Roslyn. ERR_BadAsyncReturn = 1983, ERR_BadAwaitInFinally = 1984, ERR_BadAwaitInCatch = 1985, ERR_BadAwaitArg = 1986, ERR_BadAsyncArgType = 1988, ERR_BadAsyncExpressionTree = 1989, //ERR_WindowsRuntimeTypesMissing = 1990, // unused in Roslyn ERR_MixingWinRTEventWithRegular = 1991, ERR_BadAwaitWithoutAsync = 1992, //ERR_MissingAsyncTypes = 1993, // unused in Roslyn ERR_BadAsyncLacksBody = 1994, ERR_BadAwaitInQuery = 1995, ERR_BadAwaitInLock = 1996, ERR_TaskRetNoObjectRequired = 1997, WRN_AsyncLacksAwaits = 1998, ERR_FileNotFound = 2001, WRN_FileAlreadyIncluded = 2002, //ERR_DuplicateResponseFile = 2003, ERR_NoFileSpec = 2005, ERR_SwitchNeedsString = 2006, ERR_BadSwitch = 2007, WRN_NoSources = 2008, ERR_OpenResponseFile = 2011, ERR_CantOpenFileWrite = 2012, ERR_BadBaseNumber = 2013, // WRN_UseNewSwitch = 2014, //unused. ERR_BinaryFile = 2015, FTL_BadCodepage = 2016, ERR_NoMainOnDLL = 2017, //FTL_NoMessagesDLL = 2018, FTL_InvalidTarget = 2019, //ERR_BadTargetForSecondInputSet = 2020, Roslyn doesn't support building two binaries at once! FTL_InvalidInputFileName = 2021, //ERR_NoSourcesInLastInputSet = 2022, Roslyn doesn't support building two binaries at once! WRN_NoConfigNotOnCommandLine = 2023, ERR_InvalidFileAlignment = 2024, //ERR_NoDebugSwitchSourceMap = 2026, no sourcemap support in Roslyn. //ERR_SourceMapFileBinary = 2027, WRN_DefineIdentifierRequired = 2029, //ERR_InvalidSourceMap = 2030, //ERR_NoSourceMapFile = 2031, //ERR_IllegalOptionChar = 2032, FTL_OutputFileExists = 2033, ERR_OneAliasPerReference = 2034, ERR_SwitchNeedsNumber = 2035, ERR_MissingDebugSwitch = 2036, ERR_ComRefCallInExpressionTree = 2037, WRN_BadUILang = 2038, ERR_InvalidFormatForGuidForOption = 2039, ERR_MissingGuidForOption = 2040, ERR_InvalidOutputName = 2041, ERR_InvalidDebugInformationFormat = 2042, ERR_LegacyObjectIdSyntax = 2043, ERR_SourceLinkRequiresPdb = 2044, ERR_CannotEmbedWithoutPdb = 2045, ERR_BadSwitchValue = 2046, // unused 2047-2999 WRN_CLS_NoVarArgs = 3000, WRN_CLS_BadArgType = 3001, // Requires SymbolDistinguisher. WRN_CLS_BadReturnType = 3002, WRN_CLS_BadFieldPropType = 3003, // WRN_CLS_BadUnicode = 3004, //unused WRN_CLS_BadIdentifierCase = 3005, WRN_CLS_OverloadRefOut = 3006, WRN_CLS_OverloadUnnamed = 3007, WRN_CLS_BadIdentifier = 3008, WRN_CLS_BadBase = 3009, WRN_CLS_BadInterfaceMember = 3010, WRN_CLS_NoAbstractMembers = 3011, WRN_CLS_NotOnModules = 3012, WRN_CLS_ModuleMissingCLS = 3013, WRN_CLS_AssemblyNotCLS = 3014, WRN_CLS_BadAttributeType = 3015, WRN_CLS_ArrayArgumentToAttribute = 3016, WRN_CLS_NotOnModules2 = 3017, WRN_CLS_IllegalTrueInFalse = 3018, WRN_CLS_MeaninglessOnPrivateType = 3019, WRN_CLS_AssemblyNotCLS2 = 3021, WRN_CLS_MeaninglessOnParam = 3022, WRN_CLS_MeaninglessOnReturn = 3023, WRN_CLS_BadTypeVar = 3024, WRN_CLS_VolatileField = 3026, WRN_CLS_BadInterface = 3027, FTL_BadChecksumAlgorithm = 3028, #endregion diagnostics introduced in C# 4 and earlier // unused 3029-3999 #region diagnostics introduced in C# 5 // 4000 unused ERR_BadAwaitArgIntrinsic = 4001, // 4002 unused ERR_BadAwaitAsIdentifier = 4003, ERR_AwaitInUnsafeContext = 4004, ERR_UnsafeAsyncArgType = 4005, ERR_VarargsAsync = 4006, ERR_ByRefTypeAndAwait = 4007, ERR_BadAwaitArgVoidCall = 4008, ERR_NonTaskMainCantBeAsync = 4009, ERR_CantConvAsyncAnonFuncReturns = 4010, ERR_BadAwaiterPattern = 4011, ERR_BadSpecialByRefLocal = 4012, ERR_SpecialByRefInLambda = 4013, WRN_UnobservedAwaitableExpression = 4014, ERR_SynchronizedAsyncMethod = 4015, ERR_BadAsyncReturnExpression = 4016, ERR_NoConversionForCallerLineNumberParam = 4017, ERR_NoConversionForCallerFilePathParam = 4018, ERR_NoConversionForCallerMemberNameParam = 4019, ERR_BadCallerLineNumberParamWithoutDefaultValue = 4020, ERR_BadCallerFilePathParamWithoutDefaultValue = 4021, ERR_BadCallerMemberNameParamWithoutDefaultValue = 4022, ERR_BadPrefer32OnLib = 4023, WRN_CallerLineNumberParamForUnconsumedLocation = 4024, WRN_CallerFilePathParamForUnconsumedLocation = 4025, WRN_CallerMemberNameParamForUnconsumedLocation = 4026, ERR_DoesntImplementAwaitInterface = 4027, ERR_BadAwaitArg_NeedSystem = 4028, ERR_CantReturnVoid = 4029, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync = 4030, ERR_SecurityCriticalOrSecuritySafeCriticalOnAsyncInClassOrStruct = 4031, ERR_BadAwaitWithoutAsyncMethod = 4032, ERR_BadAwaitWithoutVoidAsyncMethod = 4033, ERR_BadAwaitWithoutAsyncLambda = 4034, // ERR_BadAwaitWithoutAsyncAnonMeth = 4035, Merged with ERR_BadAwaitWithoutAsyncLambda in Roslyn ERR_NoSuchMemberOrExtensionNeedUsing = 4036, #endregion diagnostics introduced in C# 5 // unused 4037-4999 #region diagnostics introduced in C# 6 // WRN_UnknownOption = 5000, //unused in Roslyn ERR_NoEntryPoint = 5001, // huge gap here; available 5002-6999 ERR_UnexpectedAliasedName = 7000, ERR_UnexpectedGenericName = 7002, ERR_UnexpectedUnboundGenericName = 7003, ERR_GlobalStatement = 7006, ERR_BadUsingType = 7007, ERR_ReservedAssemblyName = 7008, ERR_PPReferenceFollowsToken = 7009, ERR_ExpectedPPFile = 7010, ERR_ReferenceDirectiveOnlyAllowedInScripts = 7011, ERR_NameNotInContextPossibleMissingReference = 7012, ERR_MetadataNameTooLong = 7013, ERR_AttributesNotAllowed = 7014, ERR_ExternAliasNotAllowed = 7015, ERR_ConflictingAliasAndDefinition = 7016, ERR_GlobalDefinitionOrStatementExpected = 7017, ERR_ExpectedSingleScript = 7018, ERR_RecursivelyTypedVariable = 7019, ERR_YieldNotAllowedInScript = 7020, ERR_NamespaceNotAllowedInScript = 7021, WRN_MainIgnored = 7022, WRN_StaticInAsOrIs = 7023, ERR_InvalidDelegateType = 7024, ERR_BadVisEventType = 7025, ERR_GlobalAttributesNotAllowed = 7026, ERR_PublicKeyFileFailure = 7027, ERR_PublicKeyContainerFailure = 7028, ERR_FriendRefSigningMismatch = 7029, ERR_CannotPassNullForFriendAssembly = 7030, ERR_SignButNoPrivateKey = 7032, WRN_DelaySignButNoKey = 7033, ERR_InvalidVersionFormat = 7034, WRN_InvalidVersionFormat = 7035, ERR_NoCorrespondingArgument = 7036, // Moot: WRN_DestructorIsNotFinalizer = 7037, ERR_ModuleEmitFailure = 7038, // ERR_NameIllegallyOverrides2 = 7039, // Not used anymore due to 'Single Meaning' relaxation changes // ERR_NameIllegallyOverrides3 = 7040, // Not used anymore due to 'Single Meaning' relaxation changes ERR_ResourceFileNameNotUnique = 7041, ERR_DllImportOnGenericMethod = 7042, ERR_EncUpdateFailedMissingAttribute = 7043, ERR_ParameterNotValidForType = 7045, ERR_AttributeParameterRequired1 = 7046, ERR_AttributeParameterRequired2 = 7047, ERR_SecurityAttributeMissingAction = 7048, ERR_SecurityAttributeInvalidAction = 7049, ERR_SecurityAttributeInvalidActionAssembly = 7050, ERR_SecurityAttributeInvalidActionTypeOrMethod = 7051, ERR_PrincipalPermissionInvalidAction = 7052, ERR_FeatureNotValidInExpressionTree = 7053, ERR_MarshalUnmanagedTypeNotValidForFields = 7054, ERR_MarshalUnmanagedTypeOnlyValidForFields = 7055, ERR_PermissionSetAttributeInvalidFile = 7056, ERR_PermissionSetAttributeFileReadError = 7057, ERR_InvalidVersionFormat2 = 7058, ERR_InvalidAssemblyCultureForExe = 7059, //ERR_AsyncBeforeVersionFive = 7060, ERR_DuplicateAttributeInNetModule = 7061, //WRN_PDBConstantStringValueTooLong = 7063, gave up on this warning ERR_CantOpenIcon = 7064, ERR_ErrorBuildingWin32Resources = 7065, // ERR_IteratorInInteractive = 7066, ERR_BadAttributeParamDefaultArgument = 7067, ERR_MissingTypeInSource = 7068, ERR_MissingTypeInAssembly = 7069, ERR_SecurityAttributeInvalidTarget = 7070, ERR_InvalidAssemblyName = 7071, //ERR_PartialTypesBeforeVersionTwo = 7072, //ERR_PartialMethodsBeforeVersionThree = 7073, //ERR_QueryBeforeVersionThree = 7074, //ERR_AnonymousTypeBeforeVersionThree = 7075, //ERR_ImplicitArrayBeforeVersionThree = 7076, //ERR_ObjectInitializerBeforeVersionThree = 7077, //ERR_LambdaBeforeVersionThree = 7078, ERR_NoTypeDefFromModule = 7079, WRN_CallerFilePathPreferredOverCallerMemberName = 7080, WRN_CallerLineNumberPreferredOverCallerMemberName = 7081, WRN_CallerLineNumberPreferredOverCallerFilePath = 7082, ERR_InvalidDynamicCondition = 7083, ERR_WinRtEventPassedByRef = 7084, //ERR_ByRefReturnUnsupported = 7085, ERR_NetModuleNameMismatch = 7086, ERR_BadModuleName = 7087, ERR_BadCompilationOptionValue = 7088, ERR_BadAppConfigPath = 7089, WRN_AssemblyAttributeFromModuleIsOverridden = 7090, ERR_CmdOptionConflictsSource = 7091, ERR_FixedBufferTooManyDimensions = 7092, ERR_CantReadConfigFile = 7093, ERR_BadAwaitInCatchFilter = 7094, WRN_FilterIsConstantTrue = 7095, ERR_EncNoPIAReference = 7096, //ERR_EncNoDynamicOperation = 7097, // dynamic operations are now allowed ERR_LinkedNetmoduleMetadataMustProvideFullPEImage = 7098, ERR_MetadataReferencesNotSupported = 7099, ERR_InvalidAssemblyCulture = 7100, ERR_EncReferenceToAddedMember = 7101, ERR_MutuallyExclusiveOptions = 7102, ERR_InvalidDebugInfo = 7103, #endregion diagnostics introduced in C# 6 // unused 7104-8000 #region more diagnostics introduced in Roslyn (C# 6) WRN_UnimplementedCommandLineSwitch = 8001, WRN_ReferencedAssemblyDoesNotHaveStrongName = 8002, ERR_InvalidSignaturePublicKey = 8003, ERR_ExportedTypeConflictsWithDeclaration = 8004, ERR_ExportedTypesConflict = 8005, ERR_ForwardedTypeConflictsWithDeclaration = 8006, ERR_ForwardedTypesConflict = 8007, ERR_ForwardedTypeConflictsWithExportedType = 8008, WRN_RefCultureMismatch = 8009, ERR_AgnosticToMachineModule = 8010, ERR_ConflictingMachineModule = 8011, WRN_ConflictingMachineAssembly = 8012, ERR_CryptoHashFailed = 8013, ERR_MissingNetModuleReference = 8014, ERR_NetModuleNameMustBeUnique = 8015, ERR_UnsupportedTransparentIdentifierAccess = 8016, ERR_ParamDefaultValueDiffersFromAttribute = 8017, WRN_UnqualifiedNestedTypeInCref = 8018, HDN_UnusedUsingDirective = 8019, HDN_UnusedExternAlias = 8020, WRN_NoRuntimeMetadataVersion = 8021, ERR_FeatureNotAvailableInVersion1 = 8022, // Note: one per version to make telemetry easier ERR_FeatureNotAvailableInVersion2 = 8023, ERR_FeatureNotAvailableInVersion3 = 8024, ERR_FeatureNotAvailableInVersion4 = 8025, ERR_FeatureNotAvailableInVersion5 = 8026, // ERR_FeatureNotAvailableInVersion6 is below ERR_FieldHasMultipleDistinctConstantValues = 8027, ERR_ComImportWithInitializers = 8028, WRN_PdbLocalNameTooLong = 8029, ERR_RetNoObjectRequiredLambda = 8030, ERR_TaskRetNoObjectRequiredLambda = 8031, WRN_AnalyzerCannotBeCreated = 8032, WRN_NoAnalyzerInAssembly = 8033, WRN_UnableToLoadAnalyzer = 8034, ERR_CantReadRulesetFile = 8035, ERR_BadPdbData = 8036, // available 8037-8039 INF_UnableToLoadSomeTypesInAnalyzer = 8040, // available 8041-8049 ERR_InitializerOnNonAutoProperty = 8050, ERR_AutoPropertyMustHaveGetAccessor = 8051, // ERR_AutoPropertyInitializerInInterface = 8052, ERR_InstancePropertyInitializerInInterface = 8053, ERR_EnumsCantContainDefaultConstructor = 8054, ERR_EncodinglessSyntaxTree = 8055, // ERR_AccessorListAndExpressionBody = 8056, Deprecated in favor of ERR_BlockBodyAndExpressionBody ERR_BlockBodyAndExpressionBody = 8057, ERR_FeatureIsExperimental = 8058, ERR_FeatureNotAvailableInVersion6 = 8059, // available 8062-8069 ERR_SwitchFallOut = 8070, // available = 8071, ERR_NullPropagatingOpInExpressionTree = 8072, WRN_NubExprIsConstBool2 = 8073, ERR_DictionaryInitializerInExpressionTree = 8074, ERR_ExtensionCollectionElementInitializerInExpressionTree = 8075, ERR_UnclosedExpressionHole = 8076, ERR_SingleLineCommentInExpressionHole = 8077, ERR_InsufficientStack = 8078, ERR_UseDefViolationProperty = 8079, ERR_AutoPropertyMustOverrideSet = 8080, ERR_ExpressionHasNoName = 8081, ERR_SubexpressionNotInNameof = 8082, ERR_AliasQualifiedNameNotAnExpression = 8083, ERR_NameofMethodGroupWithTypeParameters = 8084, ERR_NoAliasHere = 8085, ERR_UnescapedCurly = 8086, ERR_EscapedCurly = 8087, ERR_TrailingWhitespaceInFormatSpecifier = 8088, ERR_EmptyFormatSpecifier = 8089, ERR_ErrorInReferencedAssembly = 8090, ERR_ExternHasConstructorInitializer = 8091, ERR_ExpressionOrDeclarationExpected = 8092, ERR_NameofExtensionMethod = 8093, WRN_AlignmentMagnitude = 8094, ERR_ConstantStringTooLong = 8095, ERR_DebugEntryPointNotSourceMethodDefinition = 8096, ERR_LoadDirectiveOnlyAllowedInScripts = 8097, ERR_PPLoadFollowsToken = 8098, ERR_SourceFileReferencesNotSupported = 8099, ERR_BadAwaitInStaticVariableInitializer = 8100, ERR_InvalidPathMap = 8101, ERR_PublicSignButNoKey = 8102, ERR_TooManyUserStrings = 8103, ERR_PeWritingFailure = 8104, #endregion diagnostics introduced in Roslyn (C# 6) #region diagnostics introduced in C# 6 updates WRN_AttributeIgnoredWhenPublicSigning = 8105, ERR_OptionMustBeAbsolutePath = 8106, #endregion diagnostics introduced in C# 6 updates ERR_FeatureNotAvailableInVersion7 = 8107, #region diagnostics for local functions introduced in C# 7 ERR_DynamicLocalFunctionParamsParameter = 8108, ERR_ExpressionTreeContainsLocalFunction = 8110, #endregion diagnostics for local functions introduced in C# 7 #region diagnostics for instrumentation ERR_InvalidInstrumentationKind = 8111, #endregion ERR_LocalFunctionMissingBody = 8112, ERR_InvalidHashAlgorithmName = 8113, // Unused 8113, 8114, 8115 #region diagnostics for pattern-matching introduced in C# 7 ERR_ThrowMisplaced = 8115, ERR_PatternNullableType = 8116, ERR_BadPatternExpression = 8117, ERR_SwitchExpressionValueExpected = 8119, ERR_SwitchCaseSubsumed = 8120, ERR_PatternWrongType = 8121, ERR_ExpressionTreeContainsIsMatch = 8122, #endregion diagnostics for pattern-matching introduced in C# 7 #region tuple diagnostics introduced in C# 7 WRN_TupleLiteralNameMismatch = 8123, ERR_TupleTooFewElements = 8124, ERR_TupleReservedElementName = 8125, ERR_TupleReservedElementNameAnyPosition = 8126, ERR_TupleDuplicateElementName = 8127, ERR_PredefinedTypeMemberNotFoundInAssembly = 8128, ERR_MissingDeconstruct = 8129, ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable = 8130, ERR_DeconstructRequiresExpression = 8131, ERR_DeconstructWrongCardinality = 8132, ERR_CannotDeconstructDynamic = 8133, ERR_DeconstructTooFewElements = 8134, ERR_ConversionNotTupleCompatible = 8135, ERR_DeconstructionVarFormDisallowsSpecificType = 8136, ERR_TupleElementNamesAttributeMissing = 8137, ERR_ExplicitTupleElementNamesAttribute = 8138, ERR_CantChangeTupleNamesOnOverride = 8139, ERR_DuplicateInterfaceWithTupleNamesInBaseList = 8140, ERR_ImplBadTupleNames = 8141, ERR_PartialMethodInconsistentTupleNames = 8142, ERR_ExpressionTreeContainsTupleLiteral = 8143, ERR_ExpressionTreeContainsTupleConversion = 8144, #endregion tuple diagnostics introduced in C# 7 #region diagnostics for ref locals and ref returns introduced in C# 7 ERR_AutoPropertyCannotBeRefReturning = 8145, ERR_RefPropertyMustHaveGetAccessor = 8146, ERR_RefPropertyCannotHaveSetAccessor = 8147, ERR_CantChangeRefReturnOnOverride = 8148, ERR_MustNotHaveRefReturn = 8149, ERR_MustHaveRefReturn = 8150, ERR_RefReturnMustHaveIdentityConversion = 8151, ERR_CloseUnimplementedInterfaceMemberWrongRefReturn = 8152, ERR_RefReturningCallInExpressionTree = 8153, ERR_BadIteratorReturnRef = 8154, ERR_BadRefReturnExpressionTree = 8155, ERR_RefReturnLvalueExpected = 8156, ERR_RefReturnNonreturnableLocal = 8157, ERR_RefReturnNonreturnableLocal2 = 8158, ERR_RefReturnRangeVariable = 8159, ERR_RefReturnReadonly = 8160, ERR_RefReturnReadonlyStatic = 8161, ERR_RefReturnReadonly2 = 8162, ERR_RefReturnReadonlyStatic2 = 8163, // ERR_RefReturnCall = 8164, we use more general ERR_EscapeCall now // ERR_RefReturnCall2 = 8165, we use more general ERR_EscapeCall2 now ERR_RefReturnParameter = 8166, ERR_RefReturnParameter2 = 8167, ERR_RefReturnLocal = 8168, ERR_RefReturnLocal2 = 8169, ERR_RefReturnStructThis = 8170, ERR_InitializeByValueVariableWithReference = 8171, ERR_InitializeByReferenceVariableWithValue = 8172, ERR_RefAssignmentMustHaveIdentityConversion = 8173, ERR_ByReferenceVariableMustBeInitialized = 8174, ERR_AnonDelegateCantUseLocal = 8175, ERR_BadIteratorLocalType = 8176, ERR_BadAsyncLocalType = 8177, ERR_RefReturningCallAndAwait = 8178, #endregion diagnostics for ref locals and ref returns introduced in C# 7 #region stragglers for C# 7 ERR_PredefinedValueTupleTypeNotFound = 8179, // We need a specific error code for ValueTuple as an IDE codefix depends on it (AddNuget) ERR_SemiOrLBraceOrArrowExpected = 8180, ERR_NewWithTupleTypeSyntax = 8181, ERR_PredefinedValueTupleTypeMustBeStruct = 8182, ERR_DiscardTypeInferenceFailed = 8183, // ERR_MixedDeconstructionUnsupported = 8184, ERR_DeclarationExpressionNotPermitted = 8185, ERR_MustDeclareForeachIteration = 8186, ERR_TupleElementNamesInDeconstruction = 8187, ERR_ExpressionTreeContainsThrowExpression = 8188, ERR_DelegateRefMismatch = 8189, #endregion stragglers for C# 7 #region diagnostics for parse options ERR_BadSourceCodeKind = 8190, ERR_BadDocumentationMode = 8191, ERR_BadLanguageVersion = 8192, #endregion // Unused 8193-8195 #region diagnostics for out var ERR_ImplicitlyTypedOutVariableUsedInTheSameArgumentList = 8196, ERR_TypeInferenceFailedForImplicitlyTypedOutVariable = 8197, ERR_ExpressionTreeContainsOutVariable = 8198, #endregion diagnostics for out var #region more stragglers for C# 7 ERR_VarInvocationLvalueReserved = 8199, //ERR_ExpressionVariableInConstructorOrFieldInitializer = 8200, //ERR_ExpressionVariableInQueryClause = 8201, ERR_PublicSignNetModule = 8202, ERR_BadAssemblyName = 8203, ERR_BadAsyncMethodBuilderTaskProperty = 8204, // ERR_AttributesInLocalFuncDecl = 8205, ERR_TypeForwardedToMultipleAssemblies = 8206, ERR_ExpressionTreeContainsDiscard = 8207, ERR_PatternDynamicType = 8208, ERR_VoidAssignment = 8209, ERR_VoidInTuple = 8210, #endregion more stragglers for C# 7 #region diagnostics introduced for C# 7.1 ERR_Merge_conflict_marker_encountered = 8300, ERR_InvalidPreprocessingSymbol = 8301, ERR_FeatureNotAvailableInVersion7_1 = 8302, ERR_LanguageVersionCannotHaveLeadingZeroes = 8303, ERR_CompilerAndLanguageVersion = 8304, WRN_Experimental = 8305, ERR_TupleInferredNamesNotAvailable = 8306, ERR_TypelessTupleInAs = 8307, ERR_NoRefOutWhenRefOnly = 8308, ERR_NoNetModuleOutputWhenRefOutOrRefOnly = 8309, ERR_BadOpOnNullOrDefaultOrNew = 8310, // ERR_BadDynamicMethodArgDefaultLiteral = 8311, ERR_DefaultLiteralNotValid = 8312, // ERR_DefaultInSwitch = 8313, ERR_PatternWrongGenericTypeInVersion = 8314, ERR_AmbigBinaryOpsOnDefault = 8315, #endregion diagnostics introduced for C# 7.1 #region diagnostics introduced for C# 7.2 ERR_FeatureNotAvailableInVersion7_2 = 8320, WRN_UnreferencedLocalFunction = 8321, ERR_DynamicLocalFunctionTypeParameter = 8322, ERR_BadNonTrailingNamedArgument = 8323, ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation = 8324, #endregion diagnostics introduced for C# 7.2 #region diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2 ERR_RefConditionalAndAwait = 8325, ERR_RefConditionalNeedsTwoRefs = 8326, ERR_RefConditionalDifferentTypes = 8327, ERR_BadParameterModifiers = 8328, ERR_RefReadonlyNotField = 8329, ERR_RefReadonlyNotField2 = 8330, ERR_AssignReadonlyNotField = 8331, ERR_AssignReadonlyNotField2 = 8332, ERR_RefReturnReadonlyNotField = 8333, ERR_RefReturnReadonlyNotField2 = 8334, ERR_ExplicitReservedAttr = 8335, ERR_TypeReserved = 8336, ERR_RefExtensionMustBeValueTypeOrConstrainedToOne = 8337, ERR_InExtensionMustBeValueType = 8338, // ERR_BadParameterModifiersOrder = 8339, // Modifier ordering is relaxed ERR_FieldsInRoStruct = 8340, ERR_AutoPropsInRoStruct = 8341, ERR_FieldlikeEventsInRoStruct = 8342, ERR_RefStructInterfaceImpl = 8343, ERR_BadSpecialByRefIterator = 8344, ERR_FieldAutoPropCantBeByRefLike = 8345, ERR_StackAllocConversionNotPossible = 8346, ERR_EscapeCall = 8347, ERR_EscapeCall2 = 8348, ERR_EscapeOther = 8349, ERR_CallArgMixing = 8350, ERR_MismatchedRefEscapeInTernary = 8351, ERR_EscapeLocal = 8352, ERR_EscapeStackAlloc = 8353, ERR_RefReturnThis = 8354, ERR_OutAttrOnInParam = 8355, #endregion diagnostics introduced for `ref readonly`, `ref conditional` and `ref-like` features in C# 7.2 ERR_PredefinedValueTupleTypeAmbiguous3 = 8356, ERR_InvalidVersionFormatDeterministic = 8357, ERR_AttributeCtorInParameter = 8358, #region diagnostics for FilterIsConstant warning message fix WRN_FilterIsConstantFalse = 8359, WRN_FilterIsConstantFalseRedundantTryCatch = 8360, #endregion diagnostics for FilterIsConstant warning message fix ERR_ConditionalInInterpolation = 8361, ERR_CantUseVoidInArglist = 8362, ERR_InDynamicMethodArg = 8364, #region diagnostics introduced for C# 7.3 ERR_FeatureNotAvailableInVersion7_3 = 8370, WRN_AttributesOnBackingFieldsNotAvailable = 8371, ERR_DoNotUseFixedBufferAttrOnProperty = 8372, ERR_RefLocalOrParamExpected = 8373, ERR_RefAssignNarrower = 8374, ERR_NewBoundWithUnmanaged = 8375, //ERR_UnmanagedConstraintMustBeFirst = 8376, ERR_UnmanagedConstraintNotSatisfied = 8377, ERR_CantUseInOrOutInArglist = 8378, ERR_ConWithUnmanagedCon = 8379, ERR_UnmanagedBoundWithClass = 8380, ERR_InvalidStackAllocArray = 8381, ERR_ExpressionTreeContainsTupleBinOp = 8382, WRN_TupleBinopLiteralNameMismatch = 8383, ERR_TupleSizesMismatchForBinOps = 8384, ERR_ExprCannotBeFixed = 8385, ERR_InvalidObjectCreation = 8386, #endregion diagnostics introduced for C# 7.3 WRN_TypeParameterSameAsOuterMethodTypeParameter = 8387, ERR_OutVariableCannotBeByRef = 8388, ERR_OmittedTypeArgument = 8389, #region diagnostics introduced for C# 8.0 ERR_FeatureNotAvailableInVersion8 = 8400, ERR_AltInterpolatedVerbatimStringsNotAvailable = 8401, // Unused 8402 ERR_IteratorMustBeAsync = 8403, ERR_NoConvToIAsyncDisp = 8410, ERR_AwaitForEachMissingMember = 8411, ERR_BadGetAsyncEnumerator = 8412, ERR_MultipleIAsyncEnumOfT = 8413, ERR_ForEachMissingMemberWrongAsync = 8414, ERR_AwaitForEachMissingMemberWrongAsync = 8415, ERR_BadDynamicAwaitForEach = 8416, ERR_NoConvToIAsyncDispWrongAsync = 8417, ERR_NoConvToIDispWrongAsync = 8418, ERR_PossibleAsyncIteratorWithoutYield = 8419, ERR_PossibleAsyncIteratorWithoutYieldOrAwait = 8420, ERR_StaticLocalFunctionCannotCaptureVariable = 8421, ERR_StaticLocalFunctionCannotCaptureThis = 8422, ERR_AttributeNotOnEventAccessor = 8423, WRN_UnconsumedEnumeratorCancellationAttributeUsage = 8424, WRN_UndecoratedCancellationTokenParameter = 8425, ERR_MultipleEnumeratorCancellationAttributes = 8426, ERR_VarianceInterfaceNesting = 8427, ERR_ImplicitIndexIndexerWithName = 8428, ERR_ImplicitRangeIndexerWithName = 8429, // available range #region diagnostics introduced for recursive patterns ERR_WrongNumberOfSubpatterns = 8502, ERR_PropertyPatternNameMissing = 8503, ERR_MissingPattern = 8504, ERR_DefaultPattern = 8505, ERR_SwitchExpressionNoBestType = 8506, // ERR_SingleElementPositionalPatternRequiresDisambiguation = 8507, // Retired C# 8 diagnostic ERR_VarMayNotBindToType = 8508, WRN_SwitchExpressionNotExhaustive = 8509, ERR_SwitchArmSubsumed = 8510, ERR_ConstantPatternVsOpenType = 8511, WRN_CaseConstantNamedUnderscore = 8512, WRN_IsTypeNamedUnderscore = 8513, ERR_ExpressionTreeContainsSwitchExpression = 8514, ERR_SwitchGoverningExpressionRequiresParens = 8515, ERR_TupleElementNameMismatch = 8516, ERR_DeconstructParameterNameMismatch = 8517, ERR_IsPatternImpossible = 8518, WRN_GivenExpressionNeverMatchesPattern = 8519, WRN_GivenExpressionAlwaysMatchesConstant = 8520, ERR_PointerTypeInPatternMatching = 8521, ERR_ArgumentNameInITuplePattern = 8522, ERR_DiscardPatternInSwitchStatement = 8523, WRN_SwitchExpressionNotExhaustiveWithUnnamedEnumValue = 8524, // available 8525-8596 #endregion diagnostics introduced for recursive patterns WRN_ThrowPossibleNull = 8597, ERR_IllegalSuppression = 8598, // available 8599, WRN_ConvertingNullableToNonNullable = 8600, WRN_NullReferenceAssignment = 8601, WRN_NullReferenceReceiver = 8602, WRN_NullReferenceReturn = 8603, WRN_NullReferenceArgument = 8604, WRN_UnboxPossibleNull = 8605, // WRN_NullReferenceIterationVariable = 8606 (unavailable, may be used in warning suppressions in early C# 8.0 code) WRN_DisallowNullAttributeForbidsMaybeNullAssignment = 8607, WRN_NullabilityMismatchInTypeOnOverride = 8608, WRN_NullabilityMismatchInReturnTypeOnOverride = 8609, WRN_NullabilityMismatchInParameterTypeOnOverride = 8610, WRN_NullabilityMismatchInParameterTypeOnPartial = 8611, WRN_NullabilityMismatchInTypeOnImplicitImplementation = 8612, WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation = 8613, WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation = 8614, WRN_NullabilityMismatchInTypeOnExplicitImplementation = 8615, WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation = 8616, WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation = 8617, WRN_UninitializedNonNullableField = 8618, WRN_NullabilityMismatchInAssignment = 8619, WRN_NullabilityMismatchInArgument = 8620, WRN_NullabilityMismatchInReturnTypeOfTargetDelegate = 8621, WRN_NullabilityMismatchInParameterTypeOfTargetDelegate = 8622, ERR_ExplicitNullableAttribute = 8623, WRN_NullabilityMismatchInArgumentForOutput = 8624, WRN_NullAsNonNullable = 8625, //WRN_AsOperatorMayReturnNull = 8626, ERR_NullableUnconstrainedTypeParameter = 8627, ERR_AnnotationDisallowedInObjectCreation = 8628, WRN_NullableValueTypeMayBeNull = 8629, ERR_NullableOptionNotAvailable = 8630, WRN_NullabilityMismatchInTypeParameterConstraint = 8631, WRN_MissingNonNullTypesContextForAnnotation = 8632, WRN_NullabilityMismatchInConstraintsOnImplicitImplementation = 8633, WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint = 8634, ERR_TripleDotNotAllowed = 8635, ERR_BadNullableContextOption = 8636, ERR_NullableDirectiveQualifierExpected = 8637, //WRN_ConditionalAccessMayReturnNull = 8638, ERR_BadNullableTypeof = 8639, ERR_ExpressionTreeCantContainRefStruct = 8640, ERR_ElseCannotStartStatement = 8641, ERR_ExpressionTreeCantContainNullCoalescingAssignment = 8642, WRN_NullabilityMismatchInExplicitlyImplementedInterface = 8643, WRN_NullabilityMismatchInInterfaceImplementedByBase = 8644, WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList = 8645, ERR_DuplicateExplicitImpl = 8646, ERR_UsingVarInSwitchCase = 8647, ERR_GoToForwardJumpOverUsingVar = 8648, ERR_GoToBackwardJumpOverUsingVar = 8649, ERR_IsNullableType = 8650, ERR_AsNullableType = 8651, ERR_FeatureInPreview = 8652, //WRN_DefaultExpressionMayIntroduceNullT = 8653, //WRN_NullLiteralMayIntroduceNullT = 8654, WRN_SwitchExpressionNotExhaustiveForNull = 8655, WRN_ImplicitCopyInReadOnlyMember = 8656, ERR_StaticMemberCantBeReadOnly = 8657, ERR_AutoSetterCantBeReadOnly = 8658, ERR_AutoPropertyWithSetterCantBeReadOnly = 8659, ERR_InvalidPropertyReadOnlyMods = 8660, ERR_DuplicatePropertyReadOnlyMods = 8661, ERR_FieldLikeEventCantBeReadOnly = 8662, ERR_PartialMethodReadOnlyDifference = 8663, ERR_ReadOnlyModMissingAccessor = 8664, ERR_OverrideRefConstraintNotSatisfied = 8665, ERR_OverrideValConstraintNotSatisfied = 8666, WRN_NullabilityMismatchInConstraintsOnPartialImplementation = 8667, ERR_NullableDirectiveTargetExpected = 8668, WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode = 8669, WRN_NullReferenceInitializer = 8670, ERR_MultipleAnalyzerConfigsInSameDir = 8700, ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation = 8701, ERR_RuntimeDoesNotSupportDefaultInterfaceImplementationForMember = 8702, ERR_InvalidModifierForLanguageVersion = 8703, ERR_ImplicitImplementationOfNonPublicInterfaceMember = 8704, ERR_MostSpecificImplementationIsNotFound = 8705, ERR_LanguageVersionDoesNotSupportDefaultInterfaceImplementationForMember = 8706, ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember = 8707, //ERR_NotBaseOrImplementedInterface = 8708, //ERR_NotImplementedInBase = 8709, //ERR_NotDeclaredInBase = 8710, ERR_DefaultInterfaceImplementationInNoPIAType = 8711, ERR_AbstractEventHasAccessors = 8712, //ERR_NotNullConstraintMustBeFirst = 8713, WRN_NullabilityMismatchInTypeParameterNotNullConstraint = 8714, ERR_DuplicateNullSuppression = 8715, ERR_DefaultLiteralNoTargetType = 8716, ERR_ReAbstractionInNoPIAType = 8750, #endregion diagnostics introduced for C# 8.0 #region diagnostics introduced in C# 9.0 ERR_InternalError = 8751, ERR_ImplicitObjectCreationIllegalTargetType = 8752, ERR_ImplicitObjectCreationNotValid = 8753, ERR_ImplicitObjectCreationNoTargetType = 8754, ERR_BadFuncPointerParamModifier = 8755, ERR_BadFuncPointerArgCount = 8756, ERR_MethFuncPtrMismatch = 8757, ERR_FuncPtrRefMismatch = 8758, ERR_FuncPtrMethMustBeStatic = 8759, ERR_ExternEventInitializer = 8760, ERR_AmbigBinaryOpsOnUnconstrainedDefault = 8761, WRN_ParameterConditionallyDisallowsNull = 8762, WRN_ShouldNotReturn = 8763, WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride = 8764, WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride = 8765, WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation = 8766, WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation = 8767, WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation = 8768, WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation = 8769, WRN_DoesNotReturnMismatch = 8770, ERR_NoOutputDirectory = 8771, ERR_StdInOptionProvidedButConsoleInputIsNotRedirected = 8772, ERR_FeatureNotAvailableInVersion9 = 8773, WRN_MemberNotNull = 8774, WRN_MemberNotNullWhen = 8775, WRN_MemberNotNullBadMember = 8776, WRN_ParameterDisallowsNull = 8777, WRN_ConstOutOfRangeChecked = 8778, ERR_DuplicateInterfaceWithDifferencesInBaseList = 8779, ERR_DesignatorBeneathPatternCombinator = 8780, ERR_UnsupportedTypeForRelationalPattern = 8781, ERR_RelationalPatternWithNaN = 8782, ERR_ConditionalOnLocalFunction = 8783, WRN_GeneratorFailedDuringInitialization = 8784, WRN_GeneratorFailedDuringGeneration = 8785, ERR_WrongFuncPtrCallingConvention = 8786, ERR_MissingAddressOf = 8787, ERR_CannotUseReducedExtensionMethodInAddressOf = 8788, ERR_CannotUseFunctionPointerAsFixedLocal = 8789, ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer = 8790, ERR_ExpressionTreeContainsFromEndIndexExpression = 8791, ERR_ExpressionTreeContainsRangeExpression = 8792, WRN_GivenExpressionAlwaysMatchesPattern = 8793, WRN_IsPatternAlways = 8794, ERR_PartialMethodWithAccessibilityModsMustHaveImplementation = 8795, ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods = 8796, ERR_PartialMethodWithOutParamMustHaveAccessMods = 8797, ERR_PartialMethodWithExtendedModMustHaveAccessMods = 8798, ERR_PartialMethodAccessibilityDifference = 8799, ERR_PartialMethodExtendedModDifference = 8800, ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement = 8801, ERR_SimpleProgramMultipleUnitsWithTopLevelStatements = 8802, ERR_TopLevelStatementAfterNamespaceOrType = 8803, ERR_SimpleProgramDisallowsMainType = 8804, ERR_SimpleProgramNotAnExecutable = 8805, ERR_UnsupportedCallingConvention = 8806, ERR_InvalidFunctionPointerCallingConvention = 8807, ERR_InvalidFuncPointerReturnTypeModifier = 8808, ERR_DupReturnTypeMod = 8809, ERR_AddressOfMethodGroupInExpressionTree = 8810, ERR_CannotConvertAddressOfToDelegate = 8811, ERR_AddressOfToNonFunctionPointer = 8812, ERR_ModuleInitializerMethodMustBeOrdinary = 8813, ERR_ModuleInitializerMethodMustBeAccessibleOutsideTopLevelType = 8814, ERR_ModuleInitializerMethodMustBeStaticParameterlessVoid = 8815, ERR_ModuleInitializerMethodAndContainingTypesMustNotBeGeneric = 8816, ERR_PartialMethodReturnTypeDifference = 8817, ERR_PartialMethodRefReturnDifference = 8818, WRN_NullabilityMismatchInReturnTypeOnPartial = 8819, ERR_StaticAnonymousFunctionCannotCaptureVariable = 8820, ERR_StaticAnonymousFunctionCannotCaptureThis = 8821, ERR_OverrideDefaultConstraintNotSatisfied = 8822, ERR_DefaultConstraintOverrideOnly = 8823, WRN_ParameterNotNullIfNotNull = 8824, WRN_ReturnNotNullIfNotNull = 8825, WRN_PartialMethodTypeDifference = 8826, ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses = 8830, ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses = 8831, WRN_SwitchExpressionNotExhaustiveWithWhen = 8846, WRN_SwitchExpressionNotExhaustiveForNullWithWhen = 8847, WRN_PrecedenceInversion = 8848, ERR_ExpressionTreeContainsWithExpression = 8849, WRN_AnalyzerReferencesFramework = 8850, // WRN_EqualsWithoutGetHashCode is for object.Equals and works for classes. // WRN_RecordEqualsWithoutGetHashCode is for IEquatable<T>.Equals and works for records. WRN_RecordEqualsWithoutGetHashCode = 8851, ERR_AssignmentInitOnly = 8852, ERR_CantChangeInitOnlyOnOverride = 8853, ERR_CloseUnimplementedInterfaceMemberWrongInitOnly = 8854, ERR_ExplicitPropertyMismatchInitOnly = 8855, ERR_BadInitAccessor = 8856, ERR_InvalidWithReceiverType = 8857, ERR_CannotClone = 8858, ERR_CloneDisallowedInRecord = 8859, WRN_RecordNamedDisallowed = 8860, ERR_UnexpectedArgumentList = 8861, ERR_UnexpectedOrMissingConstructorInitializerInRecord = 8862, ERR_MultipleRecordParameterLists = 8863, ERR_BadRecordBase = 8864, ERR_BadInheritanceFromRecord = 8865, ERR_BadRecordMemberForPositionalParameter = 8866, ERR_NoCopyConstructorInBaseType = 8867, ERR_CopyConstructorMustInvokeBaseCopyConstructor = 8868, ERR_DoesNotOverrideMethodFromObject = 8869, ERR_SealedAPIInRecord = 8870, ERR_DoesNotOverrideBaseMethod = 8871, ERR_NotOverridableAPIInRecord = 8872, ERR_NonPublicAPIInRecord = 8873, ERR_SignatureMismatchInRecord = 8874, ERR_NonProtectedAPIInRecord = 8875, ERR_DoesNotOverrideBaseEqualityContract = 8876, ERR_StaticAPIInRecord = 8877, ERR_CopyConstructorWrongAccessibility = 8878, ERR_NonPrivateAPIInRecord = 8879, // The following warnings correspond to errors of the same name, but are reported // when a definite assignment issue is reported due to private fields imported from metadata. WRN_UnassignedThisAutoProperty = 8880, WRN_UnassignedThis = 8881, WRN_ParamUnassigned = 8882, WRN_UseDefViolationProperty = 8883, WRN_UseDefViolationField = 8884, WRN_UseDefViolationThis = 8885, WRN_UseDefViolationOut = 8886, WRN_UseDefViolation = 8887, ERR_CannotSpecifyManagedWithUnmanagedSpecifiers = 8888, ERR_RuntimeDoesNotSupportUnmanagedDefaultCallConv = 8889, ERR_TypeNotFound = 8890, ERR_TypeMustBePublic = 8891, WRN_SyncAndAsyncEntryPoints = 8892, ERR_InvalidUnmanagedCallersOnlyCallConv = 8893, ERR_CannotUseManagedTypeInUnmanagedCallersOnly = 8894, ERR_UnmanagedCallersOnlyMethodOrTypeCannotBeGeneric = 8895, ERR_UnmanagedCallersOnlyRequiresStatic = 8896, // The following warnings correspond to errors of the same name, but are reported // as warnings on interface methods and properties due in warning level 5. They // were not reported at all prior to level 5. WRN_ParameterIsStaticClass = 8897, WRN_ReturnTypeIsStaticClass = 8898, ERR_EntryPointCannotBeUnmanagedCallersOnly = 8899, ERR_ModuleInitializerCannotBeUnmanagedCallersOnly = 8900, ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly = 8901, ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate = 8902, ERR_InitCannotBeReadonly = 8903, ERR_UnexpectedVarianceStaticMember = 8904, ERR_FunctionPointersCannotBeCalledWithNamedArguments = 8905, ERR_EqualityContractRequiresGetter = 8906, WRN_UnreadRecordParameter = 8907, ERR_BadFieldTypeInRecord = 8908, WRN_DoNotCompareFunctionPointers = 8909, ERR_RecordAmbigCtor = 8910, ERR_FunctionPointerTypesInAttributeNotSupported = 8911, #endregion diagnostics introduced for C# 9.0 #region diagnostics introduced for C# 10.0 ERR_InheritingFromRecordWithSealedToString = 8912, ERR_HiddenPositionalMember = 8913, ERR_GlobalUsingInNamespace = 8914, ERR_GlobalUsingOutOfOrder = 8915, ERR_AttributesRequireParenthesizedLambdaExpression = 8916, ERR_CannotInferDelegateType = 8917, ERR_InvalidNameInSubpattern = 8918, ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces = 8919, ERR_GenericConstraintNotSatisfiedInterfaceWithStaticAbstractMembers = 8920, ERR_BadAbstractUnaryOperatorSignature = 8921, ERR_BadAbstractIncDecSignature = 8922, ERR_BadAbstractIncDecRetType = 8923, ERR_BadAbstractBinaryOperatorSignature = 8924, ERR_BadAbstractShiftOperatorSignature = 8925, ERR_BadAbstractStaticMemberAccess = 8926, ERR_ExpressionTreeContainsAbstractStaticMemberAccess = 8927, ERR_CloseUnimplementedInterfaceMemberNotStatic = 8928, ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfacesForMember = 8929, ERR_ExplicitImplementationOfOperatorsMustBeStatic = 8930, ERR_AbstractConversionNotInvolvingContainedType = 8931, ERR_InterfaceImplementedByUnmanagedCallersOnlyMethod = 8932, HDN_DuplicateWithGlobalUsing = 8933, ERR_CantConvAnonMethReturnType = 8934, ERR_BuilderAttributeDisallowed = 8935, ERR_FeatureNotAvailableInVersion10 = 8936, ERR_SimpleProgramIsEmpty = 8937, ERR_LineSpanDirectiveInvalidValue = 8938, ERR_LineSpanDirectiveEndLessThanStart = 8939, ERR_WrongArityAsyncReturn = 8940, ERR_InterpolatedStringHandlerMethodReturnMalformed = 8941, ERR_InterpolatedStringHandlerMethodReturnInconsistent = 8942, ERR_NullInvalidInterpolatedStringHandlerArgumentName = 8943, ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName = 8944, ERR_InvalidInterpolatedStringHandlerArgumentName = 8945, ERR_TypeIsNotAnInterpolatedStringHandlerType = 8946, WRN_ParameterOccursAfterInterpolatedStringHandlerParameter = 8947, ERR_CannotUseSelfAsInterpolatedStringHandlerArgument = 8948, ERR_InterpolatedStringHandlerArgumentAttributeMalformed = 8949, ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString = 8950, ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified = 8951, ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion = 8952, ERR_InterpolatedStringHandlerCreationCannotUseDynamic = 8953, ERR_MultipleFileScopedNamespace = 8954, ERR_FileScopedAndNormalNamespace = 8955, ERR_FileScopedNamespaceNotBeforeAllMembers = 8956, ERR_NoImplicitConvTargetTypedConditional = 8957, ERR_NonPublicParameterlessStructConstructor = 8958, ERR_NoConversionForCallerArgumentExpressionParam = 8959, WRN_CallerLineNumberPreferredOverCallerArgumentExpression = 8960, WRN_CallerFilePathPreferredOverCallerArgumentExpression = 8961, WRN_CallerMemberNamePreferredOverCallerArgumentExpression = 8962, WRN_CallerArgumentExpressionAttributeHasInvalidParameterName = 8963, ERR_BadCallerArgumentExpressionParamWithoutDefaultValue = 8964, WRN_CallerArgumentExpressionAttributeSelfReferential = 8965, WRN_CallerArgumentExpressionParamForUnconsumedLocation = 8966, ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString = 8967, #endregion // Note: you will need to re-generate compiler code after adding warnings (eng\generate-compiler-code.cmd) } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Security.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Security : WellKnownAttributesTestBase { #region Functional Tests [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void HostProtectionSecurityAttribute() { string source = @" [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct EventDescriptor { }"; Func<bool, Action<ModuleSymbol>> attributeValidator = isFromSource => (ModuleSymbol module) => { var assembly = module.ContainingAssembly; var type = (Cci.ITypeDefinition)module.GlobalNamespace.GetMember("EventDescriptor").GetCciAdapter(); if (isFromSource) { var sourceAssembly = (SourceAssemblySymbol)assembly; var compilation = sourceAssembly.DeclaringCompilation; Assert.True(type.HasDeclarativeSecurity); IEnumerable<Cci.SecurityAttribute> typeSecurityAttributes = type.SecurityAttributes; // Get System.Security.Permissions.HostProtection var emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute"); NamedTypeSymbol hostProtectionAttr = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(ref emittedName, true); Assert.NotNull(hostProtectionAttr); // Verify type security attributes Assert.Equal(1, typeSecurityAttributes.Count()); // Verify [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] var securityAttribute = typeSecurityAttributes.First(); Assert.Equal(DeclarativeSecurityAction.LinkDemand, securityAttribute.Action); var typeAttribute = (CSharpAttributeData)securityAttribute.Attribute; Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass); Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length); typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, true); } }; CompileAndVerifyWithMscorlib40(source, symbolValidator: attributeValidator(false), sourceSymbolValidator: attributeValidator(true)); } [Fact, WorkItem(544956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544956")] public void SuppressUnmanagedCodeSecurityAttribute() { string source = @" [System.Security.SuppressUnmanagedCodeSecurityAttribute] class Goo { [System.Security.SuppressUnmanagedCodeSecurityAttribute] public static void Main() {} }"; CompileAndVerify(source); } [WorkItem(544929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544929")] [Fact] public void PrincipalPermissionAttribute() { string source = @" using System.Security.Permissions; class Program { [PrincipalPermission((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [PrincipalPermission(SecurityAction.Assert)] [PrincipalPermission(SecurityAction.Demand)] [PrincipalPermission(SecurityAction.Deny)] [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 [PrincipalPermission(SecurityAction.PermitOnly)] static void Main(string[] args) { } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (9,26): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PrincipalPermission(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (10,26): error CS7052: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (11,26): error CS7052: SecurityAction value 'SecurityAction.LinkDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7048ERR_SecurityAttributeMissingAction() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : CodeAccessSecurityAttribute { public bool Field; public bool Prop { get; set; } public override IPermission CreatePermission() { return null; } public MySecurityAttribute() : base(SecurityAction.Assert) { } public MySecurityAttribute(int x, SecurityAction a1) : base(a1) { } } [MySecurityAttribute()] [MySecurityAttribute(Field = true)] [MySecurityAttribute(Field = true, Prop = true)] [MySecurityAttribute(Prop = true)] [MySecurityAttribute(Prop = true, Field = true)] [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] public class C {} "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (15,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute()] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (16,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (17,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true, Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (18,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (19,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true, Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (20,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (21,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument [PrincipalPermission()] // Invalid attribute constructor public class C { [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)' // [PrincipalPermission()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "PrincipalPermission()").WithArguments("action", "System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)").WithLocation(9, 6), // (6,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)0' // [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("PrincipalPermission", "(SecurityAction)0").WithLocation(6, 26), // (7,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)11' // [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("PrincipalPermission", "(SecurityAction)11").WithLocation(7, 26), // (8,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)(-1)' // [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("PrincipalPermission", "(SecurityAction)(-1)").WithLocation(8, 26), // (12,10): error CS0592: Attribute 'PrincipalPermission' is not valid on this declaration type. It is only valid on 'class, method' declarations. // [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "PrincipalPermission").WithArguments("PrincipalPermission", "class, method").WithLocation(12, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction_02() { string source = @" using System.Security.Permissions; public class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction action): base(action) {} public override System.Security.IPermission CreatePermission() { return null; } } namespace N { [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument [MySecurityAttribute()] // Invalid attribute constructor public class C { [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (12,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)0' // [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("MySecurityAttribute", "(SecurityAction)0").WithLocation(12, 26), // (13,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)11' // [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("MySecurityAttribute", "(SecurityAction)11").WithLocation(13, 26), // (14,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)(-1)' // [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("MySecurityAttribute", "(SecurityAction)(-1)").WithLocation(14, 26), // (15,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)' // [MySecurityAttribute()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "MySecurityAttribute()").WithArguments("action", "MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(15, 6), // (18,10): error CS0592: Attribute 'MySecurityAttribute' is not valid on this declaration type. It is only valid on 'assembly, class, struct, constructor, method' declarations. // [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "MySecurityAttribute").WithArguments("MySecurityAttribute", "assembly, class, struct, constructor, method").WithLocation(18, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForAssembly() { string source = @" using System; using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MySecurityAttribute(SecurityAction.RequestOptional)] [assembly: MySecurityAttribute(SecurityAction.RequestRefuse)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7050ERR_SecurityAttributeInvalidActionAssembly() { string source = @" using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MySecurityAttribute(SecurityAction.Assert)] [assembly: MySecurityAttribute(SecurityAction.Demand)] [assembly: MySecurityAttribute(SecurityAction.Deny)] [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,32): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (16,42): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,32): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (6,32): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (7,32): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (8,32): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (9,32): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (10,32): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (11,32): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"), // (13,42): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (14,42): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (15,42): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (16,42): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (17,42): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (18,42): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (19,42): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForTypeOrMethod() { string source = @" using System; using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class Test { [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7051ERR_SecurityAttributeInvalidActionTypeOrMethod() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class Test { [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (17,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (18,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (19,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (20,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (21,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (22,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (17,22): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (18,22): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (19,22): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (20,32): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (21,32): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (22,32): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (25,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (26,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (27,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (28,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (29,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (30,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (25,26): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (26,26): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (27,26): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (28,36): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (29,36): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (30,36): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse")); } [WorkItem(546623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546623")] [Fact] public void CS7070ERR_SecurityAttributeInvalidTarget() { string source = @" using System; using System.Security; using System.Security.Permissions; class Program { [MyPermission(SecurityAction.Demand)] public int x = 0; } [AttributeUsage(AttributeTargets.All)] class MyPermissionAttribute : CodeAccessSecurityAttribute { public MyPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return null; } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,6): error CS7070: Security attribute 'MyPermission' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. // [MyPermission(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermission")); } [WorkItem(546056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546056")] [Fact] public void TestMissingCodeAccessSecurityAttributeGeneratesNoErrors() { string source = @" namespace System { public enum AttributeTargets { All = 32767, } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets targets) { } } [AttributeUsage(AttributeTargets.All)] public class MyAttr : Attribute { } [MyAttr()] // error here public class C { } } // following are the minimum code to make Dev11 pass when using /nostdlib option namespace System { public class Object { } public abstract class ValueType { } public class Enum { } public class String { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct Char { } public struct Boolean { } public struct SByte { } public struct UInt16 { } public struct UInt32 { } public struct UInt64 { } public struct IntPtr { } public struct UIntPtr { } public class Delegate { } public class MulticastDelegate : Delegate { } public class Array { } public class Exception { } public class Type { } public struct Void { } public interface IDisposable { void Dispose(); } public class Attribute { } public class ParamArrayAttribute : Attribute { } public struct RuntimeTypeHandle { } public struct RuntimeFieldHandle { } namespace Runtime.InteropServices { public class OutAttribute : Attribute { } } namespace Reflection { public class DefaultMemberAttribute { } } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } } "; var comp = CreateEmptyCompilation(source); comp.EmitToArray(options: new EmitOptions(runtimeMetadataVersion: "v4.0.31019"), expectedWarnings: new DiagnosticDescription[0]); } #endregion #region Metadata validation tests [Fact] public void CheckSecurityAttributeOnType() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [MySecurityAttribute(SecurityAction.Assert)] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, assemblyName: "Test"); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0050" + // length of UTF-8 string "MySecurityAttribute, Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + // attr type name "\u0001" + // number of bytes in the encoding of the named arguments "\u0000" // number of named arguments }); }); } [Fact] public void CheckSecurityAttributeOnMethod() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLocalFunction() { string source = @" using System.Security.Permissions; namespace N { public class C { void M() { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] static void local1() {} } } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<M>g__local1|0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLambda() { string source = @"using System; using System.Security.Permissions; class Program { static void Main() { Action a = [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] () => { }; } }"; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<Main>b__0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } namespace N2 { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C2 { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo1() {} [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo2() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo1", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Assembly_Type_Method() { string source = @" using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Type_Method_UnsafeDll() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void GetSecurityAttributes_Type_Method_Assembly() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void PermissionSetAttribute_Fixup() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> <Permission class=""System.Security.Permissions.FileIOPermission, mscorlib"" version=""1""><AllWindows/></Permission> <Permission class=""System.Security.Permissions.RegistryPermission, mscorlib"" version=""1""><Unrestricted/></Permission> </PermissionSet>"; tempFile.WriteAllText(text); string hexFileContent = PermissionSetAttributeWithFileReference.ConvertToHex(new MemoryStream(Encoding.UTF8.GetBytes(text))); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); var resolver = new XmlFileResolver(tempDir.Path); var compilation = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); compilation.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Deny, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"MyClass", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u007f" + // length of string "System.Security.Permissions.PermissionSetAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0082" + "\u008f" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0003" + // length of string (small enough to fit in 1 byte) "Hex" + // property name "\u0082" + "\u0086" + // length of string hexFileContent // argument value }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile() { string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile_WithXmlReferenceResolver() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> </PermissionSet>"; tempFile.WriteAllText(text); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; var resolver = new XmlFileResolver(tempDir.Path); CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll.WithXmlReferenceResolver(resolver)).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7057ERR_PermissionSetAttributeFileReadError() { var tempDir = Temp.CreateDirectory(); string filePath = Path.Combine(tempDir.Path, "pset_01.xml"); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset_01.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); CSharpCompilation comp; // create file with no file sharing allowed and verify ERR_PermissionSetAttributeFileReadError during emit using (var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) { comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(tempDir.Path))); comp.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset_01.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.False(emitResult.Success); emitResult.Diagnostics.VerifyErrorCodes( Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr), Diagnostic(ErrorCode.ERR_PermissionSetAttributeFileReadError)); } } // emit succeeds now since we closed the file: using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.True(emitResult.Success); } } #endregion [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void CrashOnParamsInSecurityAttribute() { const string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction a) { } }"; CreateCompilationWithMscorlib46(source).GetDiagnostics(); } [Fact] [WorkItem(1036339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036339")] public void CrashOnOptionalParameterInSecurityAttribute() { const string source = @" using System.Security.Permissions; [A] [A()] class A : CodeAccessSecurityAttribute { public A(SecurityAction a = 0) : base(a) { } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (4,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A").WithArguments("A", "0").WithLocation(4, 2), // (5,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A()] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A()").WithArguments("A", "0").WithLocation(5, 2), // (6,7): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(6, 7)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AttributeTests_Security : WellKnownAttributesTestBase { #region Functional Tests [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void HostProtectionSecurityAttribute() { string source = @" [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public struct EventDescriptor { }"; Func<bool, Action<ModuleSymbol>> attributeValidator = isFromSource => (ModuleSymbol module) => { var assembly = module.ContainingAssembly; var type = (Cci.ITypeDefinition)module.GlobalNamespace.GetMember("EventDescriptor").GetCciAdapter(); if (isFromSource) { var sourceAssembly = (SourceAssemblySymbol)assembly; var compilation = sourceAssembly.DeclaringCompilation; Assert.True(type.HasDeclarativeSecurity); IEnumerable<Cci.SecurityAttribute> typeSecurityAttributes = type.SecurityAttributes; // Get System.Security.Permissions.HostProtection var emittedName = MetadataTypeName.FromNamespaceAndTypeName("System.Security.Permissions", "HostProtectionAttribute"); NamedTypeSymbol hostProtectionAttr = sourceAssembly.CorLibrary.LookupTopLevelMetadataType(ref emittedName, true); Assert.NotNull(hostProtectionAttr); // Verify type security attributes Assert.Equal(1, typeSecurityAttributes.Count()); // Verify [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] var securityAttribute = typeSecurityAttributes.First(); Assert.Equal(DeclarativeSecurityAction.LinkDemand, securityAttribute.Action); var typeAttribute = (CSharpAttributeData)securityAttribute.Attribute; Assert.Equal(hostProtectionAttr, typeAttribute.AttributeClass); Assert.Equal(0, typeAttribute.CommonConstructorArguments.Length); typeAttribute.VerifyNamedArgumentValue(0, "MayLeakOnAbort", TypedConstantKind.Primitive, true); } }; CompileAndVerifyWithMscorlib40(source, symbolValidator: attributeValidator(false), sourceSymbolValidator: attributeValidator(true)); } [Fact, WorkItem(544956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544956")] public void SuppressUnmanagedCodeSecurityAttribute() { string source = @" [System.Security.SuppressUnmanagedCodeSecurityAttribute] class Goo { [System.Security.SuppressUnmanagedCodeSecurityAttribute] public static void Main() {} }"; CompileAndVerify(source); } [WorkItem(544929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544929")] [Fact] public void PrincipalPermissionAttribute() { string source = @" using System.Security.Permissions; class Program { [PrincipalPermission((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [PrincipalPermission(SecurityAction.Assert)] [PrincipalPermission(SecurityAction.Demand)] [PrincipalPermission(SecurityAction.Deny)] [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 [PrincipalPermission(SecurityAction.PermitOnly)] static void Main(string[] args) { } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (9,26): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PrincipalPermission(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (10,26): error CS7052: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.InheritanceDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (11,26): error CS7052: SecurityAction value 'SecurityAction.LinkDemand' is invalid for PrincipalPermission attribute // [PrincipalPermission(SecurityAction.LinkDemand)] // CS7052 Diagnostic(ErrorCode.ERR_PrincipalPermissionInvalidAction, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7048ERR_SecurityAttributeMissingAction() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : CodeAccessSecurityAttribute { public bool Field; public bool Prop { get; set; } public override IPermission CreatePermission() { return null; } public MySecurityAttribute() : base(SecurityAction.Assert) { } public MySecurityAttribute(int x, SecurityAction a1) : base(a1) { } } [MySecurityAttribute()] [MySecurityAttribute(Field = true)] [MySecurityAttribute(Field = true, Prop = true)] [MySecurityAttribute(Prop = true)] [MySecurityAttribute(Prop = true, Field = true)] [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] public class C {} "; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (15,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute()] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (16,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (17,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Field = true, Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (18,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (19,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(Prop = true, Field = true)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (20,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(x: 0, a1: SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute"), // (21,2): error CS7048: First argument to a security attribute must be a valid SecurityAction // [MySecurityAttribute(a1: SecurityAction.Assert, x: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "MySecurityAttribute")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument [PrincipalPermission()] // Invalid attribute constructor public class C { [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (9,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)' // [PrincipalPermission()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "PrincipalPermission()").WithArguments("action", "System.Security.Permissions.PrincipalPermissionAttribute.PrincipalPermissionAttribute(System.Security.Permissions.SecurityAction)").WithLocation(9, 6), // (6,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)0' // [PrincipalPermission((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("PrincipalPermission", "(SecurityAction)0").WithLocation(6, 26), // (7,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)11' // [PrincipalPermission((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("PrincipalPermission", "(SecurityAction)11").WithLocation(7, 26), // (8,26): error CS7049: Security attribute 'PrincipalPermission' has an invalid SecurityAction value '(SecurityAction)(-1)' // [PrincipalPermission((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("PrincipalPermission", "(SecurityAction)(-1)").WithLocation(8, 26), // (12,10): error CS0592: Attribute 'PrincipalPermission' is not valid on this declaration type. It is only valid on 'class, method' declarations. // [PrincipalPermission(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "PrincipalPermission").WithArguments("PrincipalPermission", "class, method").WithLocation(12, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7049ERR_SecurityAttributeInvalidAction_02() { string source = @" using System.Security.Permissions; public class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction action): base(action) {} public override System.Security.IPermission CreatePermission() { return null; } } namespace N { [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument [MySecurityAttribute()] // Invalid attribute constructor public class C { [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target public int x; } }"; var compilation = CreateCompilationWithMscorlib40(source); compilation.VerifyDiagnostics( // (12,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)0' // [MySecurityAttribute((SecurityAction)0)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)0").WithArguments("MySecurityAttribute", "(SecurityAction)0").WithLocation(12, 26), // (13,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)11' // [MySecurityAttribute((SecurityAction)11)] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)11").WithArguments("MySecurityAttribute", "(SecurityAction)11").WithLocation(13, 26), // (14,26): error CS7049: Security attribute 'MySecurityAttribute' has an invalid SecurityAction value '(SecurityAction)(-1)' // [MySecurityAttribute((SecurityAction)(-1))] // Invalid attribute argument Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "(SecurityAction)(-1)").WithArguments("MySecurityAttribute", "(SecurityAction)(-1)").WithLocation(14, 26), // (15,6): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)' // [MySecurityAttribute()] // Invalid attribute constructor Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "MySecurityAttribute()").WithArguments("action", "MySecurityAttribute.MySecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(15, 6), // (18,10): error CS0592: Attribute 'MySecurityAttribute' is not valid on this declaration type. It is only valid on 'assembly, class, struct, constructor, method' declarations. // [MySecurityAttribute(SecurityAction.Demand)] // Invalid attribute target Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "MySecurityAttribute").WithArguments("MySecurityAttribute", "assembly, class, struct, constructor, method").WithLocation(18, 10)); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForAssembly() { string source = @" using System; using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MySecurityAttribute(SecurityAction.RequestOptional)] [assembly: MySecurityAttribute(SecurityAction.RequestRefuse)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7050ERR_SecurityAttributeInvalidActionAssembly() { string source = @" using System.Security; using System.Security.Permissions; [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MySecurityAttribute(SecurityAction.Assert)] [assembly: MySecurityAttribute(SecurityAction.Demand)] [assembly: MySecurityAttribute(SecurityAction.Deny)] [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,32): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (16,42): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,32): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (6,32): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (7,32): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (8,32): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (9,32): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (10,32): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (11,32): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MySecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly"), // (13,42): error CS7050: SecurityAction value '(SecurityAction)1' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "(SecurityAction)1").WithArguments("(SecurityAction)1"), // (14,42): error CS7050: SecurityAction value 'SecurityAction.Assert' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Assert)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Assert").WithArguments("SecurityAction.Assert"), // (15,42): error CS7050: SecurityAction value 'SecurityAction.Demand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Demand").WithArguments("SecurityAction.Demand"), // (16,42): error CS7050: SecurityAction value 'SecurityAction.Deny' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.Deny)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.Deny").WithArguments("SecurityAction.Deny"), // (17,42): error CS7050: SecurityAction value 'SecurityAction.InheritanceDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.InheritanceDemand").WithArguments("SecurityAction.InheritanceDemand"), // (18,42): error CS7050: SecurityAction value 'SecurityAction.LinkDemand' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.LinkDemand").WithArguments("SecurityAction.LinkDemand"), // (19,42): error CS7050: SecurityAction value 'SecurityAction.PermitOnly' is invalid for security attributes applied to an assembly // [assembly: MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionAssembly, "SecurityAction.PermitOnly").WithArguments("SecurityAction.PermitOnly")); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void ValidSecurityAttributeActionsForTypeOrMethod() { string source = @" using System; using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] class Test { [MySecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MySecurityAttribute(SecurityAction.Assert)] [MySecurityAttribute(SecurityAction.Demand)] [MySecurityAttribute(SecurityAction.Deny)] [MySecurityAttribute(SecurityAction.InheritanceDemand)] [MySecurityAttribute(SecurityAction.LinkDemand)] [MySecurityAttribute(SecurityAction.PermitOnly)] [MyCodeAccessSecurityAttribute((SecurityAction)1)] // Native compiler allows this security action value for type/method security attributes, but not for assembly. [MyCodeAccessSecurityAttribute(SecurityAction.Assert)] [MyCodeAccessSecurityAttribute(SecurityAction.Demand)] [MyCodeAccessSecurityAttribute(SecurityAction.Deny)] [MyCodeAccessSecurityAttribute(SecurityAction.InheritanceDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.LinkDemand)] [MyCodeAccessSecurityAttribute(SecurityAction.PermitOnly)] public static void Main() {} } "; CompileAndVerify(source); } [WorkItem(544918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544918")] [Fact] public void CS7051ERR_SecurityAttributeInvalidActionTypeOrMethod() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } class MyCodeAccessSecurityAttribute : CodeAccessSecurityAttribute { public MyCodeAccessSecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] class Test { [MySecurityAttribute(SecurityAction.RequestMinimum)] [MySecurityAttribute(SecurityAction.RequestOptional)] [MySecurityAttribute(SecurityAction.RequestRefuse)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] public static void Main() {} }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (17,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (18,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (19,22): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (20,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (21,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (22,32): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (17,22): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (18,22): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (19,22): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (20,32): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (21,32): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (22,32): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (25,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (26,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (27,26): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (28,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (29,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (30,36): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestRefuse' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestRefuse").WithArguments("System.Security.Permissions.SecurityAction.RequestRefuse", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (25,26): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (26,26): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (27,26): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MySecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse"), // (28,36): error CS7051: SecurityAction value 'SecurityAction.RequestMinimum' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestMinimum)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestMinimum").WithArguments("SecurityAction.RequestMinimum"), // (29,36): error CS7051: SecurityAction value 'SecurityAction.RequestOptional' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestOptional)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestOptional").WithArguments("SecurityAction.RequestOptional"), // (30,36): error CS7051: SecurityAction value 'SecurityAction.RequestRefuse' is invalid for security attributes applied to a type or a method // [MyCodeAccessSecurityAttribute(SecurityAction.RequestRefuse)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidActionTypeOrMethod, "SecurityAction.RequestRefuse").WithArguments("SecurityAction.RequestRefuse")); } [WorkItem(546623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546623")] [Fact] public void CS7070ERR_SecurityAttributeInvalidTarget() { string source = @" using System; using System.Security; using System.Security.Permissions; class Program { [MyPermission(SecurityAction.Demand)] public int x = 0; } [AttributeUsage(AttributeTargets.All)] class MyPermissionAttribute : CodeAccessSecurityAttribute { public MyPermissionAttribute(SecurityAction action) : base(action) { } public override IPermission CreatePermission() { return null; } }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (8,6): error CS7070: Security attribute 'MyPermission' is not valid on this declaration type. Security attributes are only valid on assembly, type and method declarations. // [MyPermission(SecurityAction.Demand)] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidTarget, "MyPermission").WithArguments("MyPermission")); } [WorkItem(546056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546056")] [Fact] public void TestMissingCodeAccessSecurityAttributeGeneratesNoErrors() { string source = @" namespace System { public enum AttributeTargets { All = 32767, } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets targets) { } } [AttributeUsage(AttributeTargets.All)] public class MyAttr : Attribute { } [MyAttr()] // error here public class C { } } // following are the minimum code to make Dev11 pass when using /nostdlib option namespace System { public class Object { } public abstract class ValueType { } public class Enum { } public class String { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct Char { } public struct Boolean { } public struct SByte { } public struct UInt16 { } public struct UInt32 { } public struct UInt64 { } public struct IntPtr { } public struct UIntPtr { } public class Delegate { } public class MulticastDelegate : Delegate { } public class Array { } public class Exception { } public class Type { } public struct Void { } public interface IDisposable { void Dispose(); } public class Attribute { } public class ParamArrayAttribute : Attribute { } public struct RuntimeTypeHandle { } public struct RuntimeFieldHandle { } namespace Runtime.InteropServices { public class OutAttribute : Attribute { } } namespace Reflection { public class DefaultMemberAttribute { } } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } } "; var comp = CreateEmptyCompilation(source); comp.EmitToArray(options: new EmitOptions(runtimeMetadataVersion: "v4.0.31019"), expectedWarnings: new DiagnosticDescription[0]); } #endregion #region Metadata validation tests [Fact] public void CheckSecurityAttributeOnType() { string source = @" using System.Security; using System.Security.Permissions; class MySecurityAttribute : SecurityAttribute { public MySecurityAttribute(SecurityAction a) : base(a) { } public override IPermission CreatePermission() { return null; } } namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [MySecurityAttribute(SecurityAction.Assert)] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, assemblyName: "Test"); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0050" + // length of UTF-8 string "MySecurityAttribute, Test, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" + // attr type name "\u0001" + // number of bytes in the encoding of the named arguments "\u0000" // number of named arguments }); }); } [Fact] public void CheckSecurityAttributeOnMethod() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLocalFunction() { string source = @" using System.Security.Permissions; namespace N { public class C { void M() { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] static void local1() {} } } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<M>g__local1|0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckSecurityAttributeOnLambda() { string source = @"using System; using System.Security.Permissions; class Program { static void Main() { Action a = [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] () => { }; } }"; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"<Main>b__0_0", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameType_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_SameMethod_DifferentAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentType_SameAction() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { } } namespace N2 { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C2 { } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_DifferentMethod_SameAction() { string source = @" using System.Security.Permissions; namespace N { public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo1() {} [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo2() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo1", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo2", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Assembly_Type_Method() { string source = @" using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (4,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void CheckMultipleSecurityAttributes_Type_Method_UnsafeDll() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }); }); } [Fact] public void GetSecurityAttributes_Type_Method_Assembly() { string source = @" using System.Security.Permissions; namespace N { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Assert, Role=@""User2"")] public class C { [PrincipalPermission(SecurityAction.Demand, Role=@""User1"")] [PrincipalPermission(SecurityAction.Demand, Role=@""User2"")] public static void Goo() {} } } "; var compilation = CreateCompilationWithMscorlib40(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1", // argument value (@"User1") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Assert, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"C", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Demand, ParentKind = SymbolKind.Method, ParentNameOpt = @"Goo", PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User1" + // argument value (@"User1") "\u0080\u0085" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.PrincipalPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u000e" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0004" + // length of UTF-8 string (small enough to fit in 1 byte) "Role" + // property name "\u0005" + // length of UTF-8 string (small enough to fit in 1 byte) "User2", // argument value (@"User2") }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void PermissionSetAttribute_Fixup() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> <Permission class=""System.Security.Permissions.FileIOPermission, mscorlib"" version=""1""><AllWindows/></Permission> <Permission class=""System.Security.Permissions.RegistryPermission, mscorlib"" version=""1""><Unrestricted/></Permission> </PermissionSet>"; tempFile.WriteAllText(text); string hexFileContent = PermissionSetAttributeWithFileReference.ConvertToHex(new MemoryStream(Encoding.UTF8.GetBytes(text))); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); var resolver = new XmlFileResolver(tempDir.Path); var compilation = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(resolver)); compilation.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.Deny, ParentKind = SymbolKind.NamedType, ParentNameOpt = @"MyClass", PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u007f" + // length of string "System.Security.Permissions.PermissionSetAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0082" + "\u008f" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u000e" + // type string "\u0003" + // length of string (small enough to fit in 1 byte) "Hex" + // property name "\u0082" + "\u0086" + // length of string hexFileContent // argument value }); }); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile() { string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; CreateCompilationWithMscorlib40(source).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [Fact] public void CS7056ERR_PermissionSetAttributeInvalidFile_WithXmlReferenceResolver() { var tempDir = Temp.CreateDirectory(); var tempFile = tempDir.CreateFile("pset.xml"); string text = @" <PermissionSet class=""System.Security.PermissionSet"" version=""1""> </PermissionSet>"; tempFile.WriteAllText(text); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""NonExistentFile.xml"")] [PermissionSetAttribute(SecurityAction.Deny, File = null)] public class MyClass { }"; var resolver = new XmlFileResolver(tempDir.Path); CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll.WithXmlReferenceResolver(resolver)).VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (5,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (4,46): error CS7056: Unable to resolve file path 'NonExistentFile.xml' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = @"NonExistentFile.xml")] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, @"File = @""NonExistentFile.xml""").WithArguments("NonExistentFile.xml", "File").WithLocation(4, 46), // (5,46): error CS7056: Unable to resolve file path '<null>' specified for the named argument 'File' for PermissionSet attribute // [PermissionSetAttribute(SecurityAction.Deny, File = null)] Diagnostic(ErrorCode.ERR_PermissionSetAttributeInvalidFile, "File = null").WithArguments("<null>", "File").WithLocation(5, 46)); } [WorkItem(545084, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545084"), WorkItem(529492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529492")] [Fact] public void CS7057ERR_PermissionSetAttributeFileReadError() { var tempDir = Temp.CreateDirectory(); string filePath = Path.Combine(tempDir.Path, "pset_01.xml"); string source = @" using System.Security.Permissions; [PermissionSetAttribute(SecurityAction.Deny, File = @""pset_01.xml"")] public class MyClass { public static void Main() { typeof(MyClass).GetCustomAttributes(false); } }"; var syntaxTree = Parse(source); CSharpCompilation comp; // create file with no file sharing allowed and verify ERR_PermissionSetAttributeFileReadError during emit using (var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) { comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(tempDir.Path))); comp.VerifyDiagnostics( // (4,25): warning CS0618: 'System.Security.Permissions.SecurityAction.Deny' is obsolete: 'Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [PermissionSetAttribute(SecurityAction.Deny, File = @"pset_01.xml")] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.Deny").WithArguments("System.Security.Permissions.SecurityAction.Deny", "Deny is obsolete and will be removed in a future release of the .NET Framework. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.False(emitResult.Success); emitResult.Diagnostics.VerifyErrorCodes( Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr), Diagnostic(ErrorCode.ERR_PermissionSetAttributeFileReadError)); } } // emit succeeds now since we closed the file: using (var output = new MemoryStream()) { var emitResult = comp.Emit(output); Assert.True(emitResult.Success); } } #endregion [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void CrashOnParamsInSecurityAttribute() { const string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction a) { } }"; CreateCompilationWithMscorlib46(source).GetDiagnostics(); } [Fact] [WorkItem(1036339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036339")] public void CrashOnOptionalParameterInSecurityAttribute() { const string source = @" using System.Security.Permissions; [A] [A()] class A : CodeAccessSecurityAttribute { public A(SecurityAction a = 0) : base(a) { } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (4,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A").WithArguments("A", "0").WithLocation(4, 2), // (5,2): error CS7049: Security attribute 'A' has an invalid SecurityAction value '0' // [A()] Diagnostic(ErrorCode.ERR_SecurityAttributeInvalidAction, "A()").WithArguments("A", "0").WithLocation(5, 2), // (6,7): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(6, 7)); } } }
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/VisualBasic/Test/Semantic/Semantics/LongTypeName.vb.txt
Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) End Sub End Module Class A1 Class A2 Class A3 Class A4 Class A5 Class A6 Class A7 Class A8 Class A9 Class A10 Class A11 Class A12 Class A13 Class A14 Class A15 Class A16 Class A17 Class A18 Class A19 Class A20 Class A21 Class A22 Class A23 Class A24 Class A25 Class A26 Class A27 Class A28 Class A29 Class A30 Class A31 Class A32 Class A33 Class A34 Class A35 Class A36 Class A37 Class A38 Class A39 Class A40 Class A41 Class A42 Class A43 Class A44 Class A45 Class A46 Class A47 Class A48 Class A49 Class A50 Class A51 Class A52 Class A53 Class A54 Class A55 Class A56 Class A57 Class A58 Class A59 Class A60 Class A61 Class A62 Class A63 Class A64 Class A65 Class A66 Class A67 Class A68 Class A69 Class A70 Class A71 Class A72 Class A73 Class A74 Class A75 Class A76 Class A77 Class A78 Class A79 Class A80 Class A81 Class A82 Class A83 Class A84 Class A85 Class A86 Class A87 Class A88 Class A89 Class A90 Class A91 Class A92 Class A93 Class A94 Class A95 Class A96 Class A97 Class A98 Class A99 Class A100 Class A101 Class A102 Class A103 Class A104 Class A105 Class A106 Class A107 Class A108 Class A109 Class A110 Class A111 Class A112 Class A113 Class A114 Class A115 Class A116 Class A117 Class A118 Class A119 Class A120 Class A121 Class A122 Class A123 Class A124 Class A125 Class A126 Class A127 Class A128 Class A129 Class A130 Class A131 Class A132 Class A133 Class A134 Class A135 Class A136 Class A137 Class A138 Class A139 Class A140 Class A141 Class A142 Class A143 Class A144 Class A145 Class A146 Class A147 Class A148 Class A149 Class A150 Class A151 Class A152 Class A153 Class A154 Class A155 Class A156 Class A157 Class A158 Class A159 Class A160 Class A161 Class A162 Class A163 Class A164 Class A165 Class A166 Class A167 Class A168 Class A169 Class A170 Class A171 Class A172 Class A173 Class A174 Class A175 Class A176 Class A177 Class A178 Class A179 Class A180 Class A181 Class A182 Class A183 Class A184 Class A185 Class A186 Class A187 Class A188 Class A189 Class A190 Class A191 Class A192 Class A193 Class A194 Class A195 Class A196 Class A197 Class A198 Class A199 Class A200 Class A201 Class A202 Class A203 Class A204 Class A205 Class A206 Class A207 Class A208 Class A209 Class A210 Class A211 Class A212 Class A213 Class A214 Class A215 Class A216 Class A217 Class A218 Class A219 Class A220 Class A221 Class A222 Class A223 Class A224 Class A225 Class A226 Class A227 End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class
Imports System Imports System.Collections.Generic Module Program Sub Main(args As String()) End Sub End Module Class A1 Class A2 Class A3 Class A4 Class A5 Class A6 Class A7 Class A8 Class A9 Class A10 Class A11 Class A12 Class A13 Class A14 Class A15 Class A16 Class A17 Class A18 Class A19 Class A20 Class A21 Class A22 Class A23 Class A24 Class A25 Class A26 Class A27 Class A28 Class A29 Class A30 Class A31 Class A32 Class A33 Class A34 Class A35 Class A36 Class A37 Class A38 Class A39 Class A40 Class A41 Class A42 Class A43 Class A44 Class A45 Class A46 Class A47 Class A48 Class A49 Class A50 Class A51 Class A52 Class A53 Class A54 Class A55 Class A56 Class A57 Class A58 Class A59 Class A60 Class A61 Class A62 Class A63 Class A64 Class A65 Class A66 Class A67 Class A68 Class A69 Class A70 Class A71 Class A72 Class A73 Class A74 Class A75 Class A76 Class A77 Class A78 Class A79 Class A80 Class A81 Class A82 Class A83 Class A84 Class A85 Class A86 Class A87 Class A88 Class A89 Class A90 Class A91 Class A92 Class A93 Class A94 Class A95 Class A96 Class A97 Class A98 Class A99 Class A100 Class A101 Class A102 Class A103 Class A104 Class A105 Class A106 Class A107 Class A108 Class A109 Class A110 Class A111 Class A112 Class A113 Class A114 Class A115 Class A116 Class A117 Class A118 Class A119 Class A120 Class A121 Class A122 Class A123 Class A124 Class A125 Class A126 Class A127 Class A128 Class A129 Class A130 Class A131 Class A132 Class A133 Class A134 Class A135 Class A136 Class A137 Class A138 Class A139 Class A140 Class A141 Class A142 Class A143 Class A144 Class A145 Class A146 Class A147 Class A148 Class A149 Class A150 Class A151 Class A152 Class A153 Class A154 Class A155 Class A156 Class A157 Class A158 Class A159 Class A160 Class A161 Class A162 Class A163 Class A164 Class A165 Class A166 Class A167 Class A168 Class A169 Class A170 Class A171 Class A172 Class A173 Class A174 Class A175 Class A176 Class A177 Class A178 Class A179 Class A180 Class A181 Class A182 Class A183 Class A184 Class A185 Class A186 Class A187 Class A188 Class A189 Class A190 Class A191 Class A192 Class A193 Class A194 Class A195 Class A196 Class A197 Class A198 Class A199 Class A200 Class A201 Class A202 Class A203 Class A204 Class A205 Class A206 Class A207 Class A208 Class A209 Class A210 Class A211 Class A212 Class A213 Class A214 Class A215 Class A216 Class A217 Class A218 Class A219 Class A220 Class A221 Class A222 Class A223 Class A224 Class A225 Class A226 Class A227 End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class End Class
-1
dotnet/roslyn
55,303
Merge release/dev17.0 to main
This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
dotnet-bot
2021-07-31T03:01:29Z
2021-07-31T04:02:27Z
32003cdb41382e31dd2799a0a15108e575071313
159cb67bb1e38f12662b22681e412c9746e7bcfb
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/InvalidGenericType.dll
MZ@ !L!This program cannot be run in DOS mode. $PELy Q!  " @@ `@4"W@  H.text  `.reloc @@Bp"H` ( *( *BSJB v4.0.30319l#~L`#Strings#US#GUID#BlobG %3 >HP X  M5BEJ<Module>SystemObject.ctorInvalidGenericType.dllmscorlibC`2T1T2DS1InvalidGenericType ER%, z\V4\"~" p"_CorDllMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PELy Q!  " @@ `@4"W@  H.text  `.reloc @@Bp"H` ( *( *BSJB v4.0.30319l#~L`#Strings#US#GUID#BlobG %3 >HP X  M5BEJ<Module>SystemObject.ctorInvalidGenericType.dllmscorlibC`2T1T2DS1InvalidGenericType ER%, z\V4\"~" p"_CorDllMainmscoree.dll% @ 2
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Test/EditAndContinue/EditAndContinueWorkspaceServiceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0", }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0", }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api; using Microsoft.CodeAnalysis.ExternalAccess.Watch.Api; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.TestGenerators; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public sealed partial class EditAndContinueWorkspaceServiceTests : TestBase { private static readonly TestComposition s_composition = FeaturesTestCompositions.Features; private static readonly ActiveStatementSpanProvider s_noActiveSpans = (_, _, _) => new(ImmutableArray<ActiveStatementSpan>.Empty); private const TargetFramework DefaultTargetFramework = TargetFramework.NetStandard20; private Func<Project, CompilationOutputs> _mockCompilationOutputsProvider; private readonly List<string> _telemetryLog; private int _telemetryId; private readonly MockManagedEditAndContinueDebuggerService _debuggerService; public EditAndContinueWorkspaceServiceTests() { _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()); _telemetryLog = new List<string>(); _debuggerService = new MockManagedEditAndContinueDebuggerService() { LoadedModules = new Dictionary<Guid, ManagedEditAndContinueAvailability>() }; } private TestWorkspace CreateWorkspace(out Solution solution, out EditAndContinueWorkspaceService service, Type[] additionalParts = null) { var workspace = new TestWorkspace(composition: s_composition.AddParts(additionalParts)); solution = workspace.CurrentSolution; service = GetEditAndContinueService(workspace); return workspace; } private static SourceText GetAnalyzerConfigText((string key, string value)[] analyzerConfig) => SourceText.From("[*.*]" + Environment.NewLine + string.Join(Environment.NewLine, analyzerConfig.Select(c => $"{c.key} = {c.value}"))); private static (Solution, Document) AddDefaultTestProject( Solution solution, string source, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { solution = AddDefaultTestProject(solution, new[] { source }, generator, additionalFileText, analyzerConfig); return (solution, solution.Projects.Single().Documents.Single()); } private static Solution AddDefaultTestProject( Solution solution, string[] sources, ISourceGenerator generator = null, string additionalFileText = null, (string key, string value)[] analyzerConfig = null) { var project = solution. AddProject("proj", "proj", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = project.Solution; if (generator != null) { solution = solution.AddAnalyzerReference(project.Id, new TestGeneratorReference(generator)); } if (additionalFileText != null) { solution = solution.AddAdditionalDocument(DocumentId.CreateNewId(project.Id), "additional", SourceText.From(additionalFileText)); } if (analyzerConfig != null) { solution = solution.AddAnalyzerConfigDocument( DocumentId.CreateNewId(project.Id), name: "config", GetAnalyzerConfigText(analyzerConfig), filePath: Path.Combine(TempRoot.Root, "config")); } Document document = null; var i = 1; foreach (var source in sources) { var fileName = $"test{i++}.cs"; document = solution.GetProject(project.Id). AddDocument(fileName, SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, fileName)); solution = document.Project.Solution; } return document.Project.Solution; } private EditAndContinueWorkspaceService GetEditAndContinueService(Workspace workspace) { var service = (EditAndContinueWorkspaceService)workspace.Services.GetRequiredService<IEditAndContinueWorkspaceService>(); var accessor = service.GetTestAccessor(); accessor.SetOutputProvider(project => _mockCompilationOutputsProvider(project)); return service; } private async Task<DebuggingSession> StartDebuggingSessionAsync( EditAndContinueWorkspaceService service, Solution solution, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var sessionId = await service.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var session = service.GetTestAccessor().GetDebuggingSession(sessionId); if (initialState != CommittedSolution.DocumentState.None) { SetDocumentsState(session, solution, initialState); } session.GetTestAccessor().SetTelemetryLogger((id, message) => _telemetryLog.Add($"{id}: {message.GetMessage()}"), () => ++_telemetryId); return session; } private void EnterBreakState( DebuggingSession session, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements = default, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { _debuggerService.GetActiveStatementsImpl = () => activeStatements.NullToEmpty(); session.BreakStateEntered(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private void ExitBreakState() { _debuggerService.GetActiveStatementsImpl = () => ImmutableArray<ManagedActiveStatementDebugInfo>.Empty; } private static void CommitSolutionUpdate(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.CommitSolutionUpdate(out var documentsToReanalyze); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static void EndDebuggingSession(DebuggingSession session, ImmutableArray<DocumentId> documentsWithRudeEdits = default) { session.EndSession(out var documentsToReanalyze, out _); AssertEx.Equal(documentsWithRudeEdits.NullToEmpty(), documentsToReanalyze); } private static async Task<(ManagedModuleUpdates updates, ImmutableArray<DiagnosticData> diagnostics)> EmitSolutionUpdateAsync( DebuggingSession session, Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider = null) { var result = await session.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider ?? s_noActiveSpans, CancellationToken.None); return (result.ModuleUpdates, result.GetDiagnosticData(solution)); } internal static void SetDocumentsState(DebuggingSession session, Solution solution, CommittedSolution.DocumentState state) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { session.LastCommittedSolution.Test_SetDocumentState(document.Id, state); } } } private static IEnumerable<string> InspectDiagnostics(ImmutableArray<DiagnosticData> actual) => actual.Select(d => $"{d.ProjectId} {InspectDiagnostic(d)}"); private static string InspectDiagnostic(DiagnosticData diagnostic) => $"{diagnostic.Severity} {diagnostic.Id}: {diagnostic.Message}"; internal static Guid ReadModuleVersionId(Stream stream) { using var peReader = new PEReader(stream); var metadataReader = peReader.GetMetadataReader(); var mvidHandle = metadataReader.GetModuleDefinition().Mvid; return metadataReader.GetGuid(mvidHandle); } private Guid EmitAndLoadLibraryToDebuggee(string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "") { var moduleId = EmitLibrary(source, sourceFilePath, encoding, assemblyName); LoadLibraryToDebuggee(moduleId); return moduleId; } private void LoadLibraryToDebuggee(Guid moduleId, ManagedEditAndContinueAvailability availability = default) { _debuggerService.LoadedModules.Add(moduleId, availability); } private Guid EmitLibrary( string source, string sourceFilePath = null, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { return EmitLibrary(new[] { (source, sourceFilePath ?? Path.Combine(TempRoot.Root, "test1.cs")) }, encoding, assemblyName, pdbFormat, generator, additionalFileText, analyzerOptions); } private Guid EmitLibrary( (string content, string filePath)[] sources, Encoding encoding = null, string assemblyName = "", DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb, ISourceGenerator generator = null, string additionalFileText = null, IEnumerable<(string, string)> analyzerOptions = null) { encoding ??= Encoding.UTF8; var parseOptions = TestOptions.RegularPreview; var trees = sources.Select(source => { var sourceText = SourceText.From(new MemoryStream(encoding.GetBytes(source.content)), encoding, checksumAlgorithm: SourceHashAlgorithm.Sha256); return SyntaxFactory.ParseSyntaxTree(sourceText, parseOptions, source.filePath); }); Compilation compilation = CSharpTestBase.CreateCompilation(trees.ToArray(), options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: assemblyName); if (generator != null) { var optionsProvider = (analyzerOptions != null) ? new EditAndContinueTestAnalyzerConfigOptionsProvider(analyzerOptions) : null; var additionalTexts = (additionalFileText != null) ? new[] { new InMemoryAdditionalText("additional_file", additionalFileText) } : null; var generatorDriver = CSharpGeneratorDriver.Create(new[] { generator }, additionalTexts, parseOptions, optionsProvider); generatorDriver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var generatorDiagnostics); generatorDiagnostics.Verify(); compilation = outputCompilation; } return EmitLibrary(compilation, pdbFormat); } private Guid EmitLibrary(Compilation compilation, DebugInformationFormat pdbFormat = DebugInformationFormat.PortablePdb) { var (peImage, pdbImage) = compilation.EmitToArrays(new EmitOptions(debugInformationFormat: pdbFormat)); var symReader = SymReaderTestHelpers.OpenDummySymReader(pdbImage); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleId = moduleMetadata.GetModuleVersionId(); // associate the binaries with the project (assumes a single project) _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenAssemblyStreamImpl = () => { var stream = new MemoryStream(); peImage.WriteToStream(stream); stream.Position = 0; return stream; }, OpenPdbStreamImpl = () => { var stream = new MemoryStream(); pdbImage.WriteToStream(stream); stream.Position = 0; return stream; } }; return moduleId; } private static SourceText CreateSourceTextFromFile(string path) { using var stream = File.OpenRead(path); return SourceText.From(stream, Encoding.UTF8, SourceHashAlgorithm.Sha256); } private static TextSpan GetSpan(string str, string substr) => new TextSpan(str.IndexOf(substr), substr.Length); private static void VerifyReadersDisposed(IEnumerable<IDisposable> readers) { foreach (var reader in readers) { Assert.Throws<ObjectDisposedException>(() => { if (reader is MetadataReaderProvider md) { md.GetMetadataReader(); } else { ((DebugInformationReaderProvider)reader).CreateEditAndContinueMethodDebugInfoReader(); } }); } } private static DocumentInfo CreateDesignTimeOnlyDocument(ProjectId projectId, string name = "design-time-only.cs", string path = "design-time-only.cs") => DocumentInfo.Create( DocumentId.CreateNewId(projectId, name), name: name, folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class DTO {}"), VersionStamp.Create(), path)), filePath: path, isGenerated: false, designTimeOnly: true, documentServiceProvider: null); internal sealed class FailingTextLoader : TextLoader { public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { Assert.True(false, $"Content of document {documentId} should never be loaded"); throw ExceptionUtilities.Unreachable; } } [Theory] [CombinatorialData] public async Task StartDebuggingSession_CapturingDocuments(bool captureAllDocuments) { var encodingA = Encoding.BigEndianUnicode; var encodingB = Encoding.Unicode; var encodingC = Encoding.GetEncoding("SJIS"); var encodingE = Encoding.UTF8; var sourceA1 = "class A {}"; var sourceB1 = "class B { int F() => 1; }"; var sourceB2 = "class B { int F() => 2; }"; var sourceB3 = "class B { int F() => 3; }"; var sourceC1 = "class C { const char L = 'ワ'; }"; var sourceD1 = "dummy code"; var sourceE1 = "class E { }"; var sourceBytesA1 = encodingA.GetBytes(sourceA1); var sourceBytesB1 = encodingB.GetBytes(sourceB1); var sourceBytesC1 = encodingC.GetBytes(sourceC1); var sourceBytesE1 = encodingE.GetBytes(sourceE1); var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllBytes(sourceBytesA1); var sourceFileB = dir.CreateFile("B.cs").WriteAllBytes(sourceBytesB1); var sourceFileC = dir.CreateFile("C.cs").WriteAllBytes(sourceBytesC1); var sourceFileD = dir.CreateFile("dummy").WriteAllText(sourceD1); var sourceFileE = dir.CreateFile("E.cs").WriteAllBytes(sourceBytesE1); var sourceTreeA1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesA1, sourceBytesA1.Length, encodingA, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileA.Path); var sourceTreeB1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesB1, sourceBytesB1.Length, encodingB, SourceHashAlgorithm.Sha256), TestOptions.Regular, sourceFileB.Path); var sourceTreeC1 = SyntaxFactory.ParseSyntaxTree(SourceText.From(sourceBytesC1, sourceBytesC1.Length, encodingC, SourceHashAlgorithm.Sha1), TestOptions.Regular, sourceFileC.Path); // E is not included in the compilation: var compilation = CSharpTestBase.CreateCompilation(new[] { sourceTreeA1, sourceTreeB1, sourceTreeC1 }, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "P"); EmitLibrary(compilation); // change content of B on disk: sourceFileB.WriteAllText(sourceB2, encodingB); // prepare workspace as if it was loaded from project files: using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var projectP = solution.AddProject("P", "P", LanguageNames.CSharp); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, encodingA), filePath: sourceFileA.Path)); var documentIdB = DocumentId.CreateNewId(projectP.Id, debugName: "B"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdB, name: "B", loader: new FileTextLoader(sourceFileB.Path, encodingB), filePath: sourceFileB.Path)); var documentIdC = DocumentId.CreateNewId(projectP.Id, debugName: "C"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdC, name: "C", loader: new FileTextLoader(sourceFileC.Path, encodingC), filePath: sourceFileC.Path)); var documentIdE = DocumentId.CreateNewId(projectP.Id, debugName: "E"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdE, name: "E", loader: new FileTextLoader(sourceFileE.Path, encodingE), filePath: sourceFileE.Path)); // check that are testing documents whose hash algorithm does not match the PDB (but the hash itself does): Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdA).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdB).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdC).GetTextSynchronously(default).ChecksumAlgorithm); Assert.Equal(SourceHashAlgorithm.Sha1, solution.GetDocument(documentIdE).GetTextSynchronously(default).ChecksumAlgorithm); // design-time-only document with and without absolute path: solution = solution. AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt1.cs", path: Path.Combine(dir.Path, "dt1.cs"))). AddDocument(CreateDesignTimeOnlyDocument(projectP.Id, name: "dt2.cs", path: "dt2.cs")); // project that does not support EnC - the contents of documents in this project shouldn't be loaded: var projectQ = solution.AddProject("Q", "Q", DummyLanguageService.LanguageName); solution = projectQ.Solution; solution = solution.AddDocument(DocumentInfo.Create( id: DocumentId.CreateNewId(projectQ.Id, debugName: "D"), name: "D", loader: new FailingTextLoader(), filePath: sourceFileD.Path)); var captureMatchingDocuments = captureAllDocuments ? ImmutableArray<DocumentId>.Empty : (from project in solution.Projects from documentId in project.DocumentIds select documentId).ToImmutableArray(); var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments, captureAllDocuments, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = debuggingSession.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)", "(C, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); // change content of B on disk again: sourceFileB.WriteAllText(sourceB3, encodingB); solution = solution.WithDocumentTextLoader(documentIdB, new FileTextLoader(sourceFileB.Path, encodingB), PreservationMode.PreserveValue); EnterBreakState(debuggingSession); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{projectP.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFileB.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); } [Fact] public async Task RunMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; await StartDebuggingSessionAsync(service, solution); // no changes: var document1 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DesignTimeOnlyDocument() { var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); var documentInfo = CreateDesignTimeOnlyDocument(document1.Project.Id); solution = solution.WithProjectOutputFilePath(document1.Project.Id, moduleFile.Path).AddDocument(documentInfo); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update a design-time-only source file: solution = solution.WithDocumentText(documentInfo.Id, SourceText.From("class UpdatedC2 {}")); var document2 = solution.GetDocument(documentInfo.Id); // no updates: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // validate solution update status and emit - changes made in design-time-only documents are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task RunMode_ProjectNotBuilt() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.Empty); await StartDebuggingSessionAsync(service, solution); // no changes: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); } [Fact] public async Task RunMode_DifferentDocumentWithSameContent() { var source = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleFile = Temp.CreateFile().WriteAllBytes(TestResources.Basic.Members); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source); solution = solution.WithProjectOutputFilePath(document.Project.Id, moduleFile.Path); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // update the document var document1 = solution.GetDocument(document.Id); solution = solution.WithDocumentText(document.Id, SourceText.From(source)); var document2 = solution.GetDocument(document.Id); Assert.Equal(document1.Id, document2.Id); Assert.NotSame(document1, document2); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); // validate solution update status and emit - changes made during run mode are ignored: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ProjectThatDoesNotSupportEnC() { using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("dummy2")); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Fact] public async Task BreakMode_DesignTimeOnlyDocument_Dynamic() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C {}"); var documentInfo = DocumentInfo.Create( DocumentId.CreateNewId(document.Project.Id), name: "design-time-only.cs", folders: Array.Empty<string>(), sourceCodeKind: SourceCodeKind.Regular, loader: TextLoader.From(TextAndVersion.Create(SourceText.From("class D {}"), VersionStamp.Create(), "design-time-only.cs")), filePath: "design-time-only.cs", isGenerated: false, designTimeOnly: true, documentServiceProvider: null); solution = solution.AddDocument(documentInfo); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.GetDocument(documentInfo.Id); solution = solution.WithDocumentText(document1.Id, SourceText.From("class E {}")); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_DesignTimeOnlyDocument_Wpf(bool delayLoad) { var sourceA = "class A { public void M() { } }"; var sourceB = "class B { public void M() { } }"; var sourceC = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("a.cs").WriteAllText(sourceA); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); var documentB = documentA.Project. AddDocument("b.g.i.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: "b.g.i.cs"); var documentC = documentB.Project. AddDocument("c.g.i.vb", SourceText.From(sourceC, Encoding.UTF8), filePath: "c.g.i.vb"); solution = documentC.Project.Solution; // only compile A; B and C are design-time-only: var moduleId = EmitLibrary(sourceA, sourceFilePath: sourceFileA.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var sessionId = await service.StartDebuggingSessionAsync(solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: false, reportDiagnostics: true, CancellationToken.None); var debuggingSession = service.GetTestAccessor().GetDebuggingSession(sessionId); EnterBreakState(debuggingSession); // change the source (rude edit): solution = solution.WithDocumentText(documentB.Id, SourceText.From("class B { public void RenamedMethod() { } }")); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { public void RenamedMethod() { } }")); var documentB2 = solution.GetDocument(documentB.Id); var documentC2 = solution.GetDocument(documentC.Id); // no Rude Edits reported: Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentB2, s_noActiveSpans, CancellationToken.None)); Assert.Empty(await service.GetDocumentDiagnosticsAsync(documentC2, s_noActiveSpans, CancellationToken.None)); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); if (delayLoad) { LoadLibraryToDebuggee(moduleId); // validate solution update status and emit: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); } EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task ErrorReadingModuleFile(bool breakMode) { // module file is empty, which will cause a read error: var moduleFile = Temp.CreateFile(); string expectedErrorMessage = null; try { using var stream = File.OpenRead(moduleFile.Path); using var peReader = new PEReader(stream); _ = peReader.GetMetadataReader(); } catch (Exception e) { expectedErrorMessage = e.Message; } using var _w = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }")); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, moduleFile.Path, expectedErrorMessage)}" }, InspectDiagnostics(emitDiagnostics)); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=False", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } } [Fact] public async Task BreakMode_ErrorReadingPdbFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId) { OpenPdbStreamImpl = () => { throw new IOException("Error"); } }; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=1|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1" }, _telemetryLog); } [Fact] public async Task BreakMode_ErrorReadingSourceFile() { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); using var fileLock = File.Open(sourceFile.Path, FileMode.Open, FileAccess.Read, FileShare.None); // error not reported here since it might be intermittent and will be reported if the issue persist when applying the update: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // an error occurred so we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // try apply changes: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1006: {string.Format(FeaturesResources.UnableToReadSourceFileOrPdb, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); fileLock.Dispose(); // try apply changes again: (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.NotEmpty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Theory] [CombinatorialData] public async Task FileAdded(bool breakMode) { var sourceA = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceB = "class C2 {}"; var sourceFileA = Temp.CreateFile().WriteAllText(sourceA); var sourceFileB = Temp.CreateFile().WriteAllText(sourceB); using var _ = CreateWorkspace(out var solution, out var service); var documentA = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(sourceA, Encoding.UTF8), filePath: sourceFileA.Path); solution = documentA.Project.Solution; // Source B will be added while debugging. EmitAndLoadLibraryToDebuggee(sourceA, sourceFilePath: sourceFileA.Path); var project = documentA.Project; var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // add a source file: var documentB = project.AddDocument("file2.cs", SourceText.From(sourceB, Encoding.UTF8), filePath: sourceFileB.Path); solution = documentB.Project.Solution; documentB = solution.GetDocument(documentB.Id); var diagnostics2 = await service.GetDocumentDiagnosticsAsync(documentB, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics2); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Fact] public async Task BreakMode_ModuleDisallowsEditAndContinue() { var moduleId = Guid.NewGuid(); var source1 = @" class C1 { void M() { System.Console.WriteLine(1); System.Console.WriteLine(2); System.Console.WriteLine(3); } }"; var source2 = @" class C1 { void M() { System.Console.WriteLine(9); System.Console.WriteLine(); System.Console.WriteLine(30); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); LoadLibraryToDebuggee(moduleId, new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.NotAllowedForRuntime, "*message*")); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // We do not report module diagnostics until emit. // This is to make the analysis deterministic (not dependent on the current state of the debuggee). var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{document2.Project.Id} Error ENC2016: {string.Format(FeaturesResources.EditAndContinueDisallowedByProject, document2.Project.Name, "*message*")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC2016" }, _telemetryLog); } [Fact] public async Task BreakMode_Encodings() { var source1 = "class C1 { void M() { System.Console.WriteLine(\"ã\"); } }"; var encoding = Encoding.GetEncoding(1252); var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1, encoding); using var _ = CreateWorkspace(out var solution, out var service); var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, encoding), filePath: sourceFile.Path); var documentId = document1.Id; var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path, encoding: encoding); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // Emulate opening the file, which will trigger "out-of-sync" check. // Since we find content matching the PDB checksum we update the committed solution with this source text. // If we used wrong encoding this would lead to a false change detected below. var currentDocument = solution.GetDocument(documentId); await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); // EnC service queries for a document, which triggers read of the source file from disk. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task RudeEdits(bool breakMode) { var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M1() { System.Console.WriteLine(1); } }"; var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_SourceGenerators() { var sourceV1 = @" /* GENERATE: class G { int X1 => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X2 => 1; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1, generator: generator); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source: var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var generatedDocument = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync()).Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(generatedDocument, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.property_) }, diagnostics1.Select(d => $"{d.Id}: {d.GetMessage()}")); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(generatedDocument.Id)); } [Theory] [CombinatorialData] public async Task RudeEdits_DocumentOutOfSync(bool breakMode) { var source0 = "class C1 { void M() { System.Console.WriteLine(0); } }"; var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void RenamedMethod() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs"); using var _ = CreateWorkspace(out var solution, out var service); var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; // compile with source0: var moduleId = EmitAndLoadLibraryToDebuggee(source0, sourceFilePath: sourceFile.Path); // update the file with source1 before session starts: sourceFile.WriteAllText(source1); // source1 is reflected in workspace before session starts: var document1 = project.AddDocument("a.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); solution = document1.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (rude edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(source2)); var document2 = solution.GetDocument(document1.Id); // no Rude Edits, since the document is out-of-sync var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // update the file to match the build: sourceFile.WriteAllText(source0); // we do not reload the content of out-of-sync file for analyzer query: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // debugger query will trigger reload of out-of-sync file content: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); // now we see the rude edit: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal(new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=True", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } else { AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount=0", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=True|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=1|EmitDeltaErrorIdCount=0|InBreakState=False", "Debugging_EncSession_EditSession_RudeEdit: SessionId=1|EditSessionId=2|RudeEditKind=20|RudeEditSyntaxKind=8875|RudeEditBlocking=True" }, _telemetryLog); } } [Fact] public async Task BreakMode_RudeEdits_DocumentWithoutSequencePoints() { var source1 = "abstract class C { public abstract void M(); }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit since the base document content matches the PDB checksum, so the document is not out-of-sync): solution = solution.WithDocumentText(document1.Id, SourceText.From("abstract class C { public abstract void M(); public abstract void N(); }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0023: " + string.Format(FeaturesResources.Adding_an_abstract_0_or_overriding_an_inherited_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_RudeEdits_DelayLoadedModule() { var source1 = "class C { public void M() { } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("a.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source1, Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(source1, sourceFilePath: sourceFile.Path); // do not initialize the document state - we will detect the state based on the PDB content. var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // change the source (rude edit) before the library is loaded: solution = solution.WithDocumentText(document1.Id, SourceText.From("class C { public void Renamed() { } }")); var document2 = solution.Projects.Single().Documents.Single(); // Rude Edits reported: var diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // load library to the debuggee: LoadLibraryToDebuggee(moduleId); // Rude Edits still reported: diagnostics = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession, documentsWithRudeEdits: ImmutableArray.Create(document2.Id)); } [Fact] public async Task BreakMode_SyntaxError() { var moduleId = Guid.NewGuid(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { ")); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=True|HadRudeEdits=False|HadValidChanges=False|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True" }, _telemetryLog); } [Fact] public async Task BreakMode_SemanticError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (compilation error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { int i = 0L; System.Console.WriteLine(i); } }", Encoding.UTF8)); var document2 = solution.Projects.Single().Documents.Single(); // compilation errors are not reported via EnC diagnostic analyzer: var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // The EnC analyzer does not check for and block on all semantic errors as they are already reported by diagnostic analyzer. // Blocking update on semantic errors would be possible, but the status check is only an optimization to avoid emitting. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); Assert.Empty(updates.Updates); // TODO: https://github.com/dotnet/roslyn/issues/36061 // Semantic errors should not be reported in emit diagnostics. AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS0266: {string.Format(CSharpResources.ERR_NoImplicitConvCast, "long", "int")}" }, InspectDiagnostics(emitDiagnostics)); EndDebuggingSession(debuggingSession); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS0266" }, _telemetryLog); } [Fact] public async Task BreakMode_FileStatus_CompilationError() { using var _ = CreateWorkspace(out var solution, out var service); solution = solution. AddProject("A", "A", "C#"). AddDocument("A.cs", "class Program { void Main() { System.Console.WriteLine(1); } }", filePath: "A.cs").Project.Solution. AddProject("B", "B", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("B.cs", "class B {}", filePath: "B.cs").Project.Solution. AddProject("C", "C", "C#"). AddDocument("Common.cs", "class Common {}", filePath: "Common.cs").Project. AddDocument("C.cs", "class C {}", filePath: "C.cs").Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change C.cs to have a compilation error: var projectC = solution.GetProjectsByName("C").Single(); var documentC = projectC.Documents.Single(d => d.Name == "C.cs"); solution = solution.WithDocumentText(documentC.Id, SourceText.From("class C { void M() { ")); // Common.cs is included in projects B and C. Both of these projects must have no errors, otherwise update is blocked. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "Common.cs", CancellationToken.None)); // No changes in project containing file B.cs. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: "B.cs", CancellationToken.None)); // All projects must have no errors. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_EmitError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit but passing no encoding to emulate emit error): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", encoding: null)); var document2 = solution.Projects.Single().Documents.Single(); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document2.Project.Id} Error CS8055: {string.Format(CSharpResources.ERR_EncodinglessSyntaxTree)}" }, InspectDiagnostics(emitDiagnostics)); // no emitted delta: Assert.Empty(updates.Updates); // no pending update: Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); Assert.Throws<InvalidOperationException>(() => debuggingSession.CommitSolutionUpdate(out var _)); Assert.Throws<InvalidOperationException>(() => debuggingSession.DiscardSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // solution update status after discarding an update (still has update ready): Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=CS8055" }, _telemetryLog); } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_ApplyBeforeFileWatcherEvent(bool saveDocument) { // Scenarios tested: // // SaveDocument=true // workspace: --V0-------------|--V2--------|------------| // file system: --V0---------V1--|-----V2-----|------------| // \--build--/ F5 ^ F10 ^ F10 // save file watcher: no-op // SaveDocument=false // workspace: --V0-------------|--V2--------|----V1------| // file system: --V0---------V1--|------------|------------| // \--build--/ F5 F10 ^ F10 // file watcher: workspace update var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var documentId = document1.Id; solution = document1.Project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // The user opens the source file and changes the source before Roslyn receives file watcher event. var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; solution = solution.WithDocumentText(documentId, SourceText.From(source2, Encoding.UTF8)); var document2 = solution.GetDocument(documentId); // Save the document: if (saveDocument) { await debuggingSession.OnSourceFileUpdatedAsync(document2); sourceFile.WriteAllText(source2); } // EnC service queries for a document, which triggers read of the source file from disk. Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); ExitBreakState(); EnterBreakState(debuggingSession); // file watcher updates the workspace: solution = solution.WithDocumentText(documentId, CreateSourceTextFromFile(sourceFile.Path)); var document3 = solution.Projects.Single().Documents.Single(); var hasChanges = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); if (saveDocument) { Assert.False(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); } else { Assert.True(hasChanges); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); } ExitBreakState(); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_FileUpdateNotObservedBeforeDebuggingSessionStart() { // workspace: --V0--------------V2-------|--------V3------------------V1--------------| // file system: --V0---------V1-----V2-----|------------------------------V1------------| // \--build--/ ^save F5 ^ ^F10 (no change) ^save F10 (ok) // file watcher: no-op // build updates file from V0 -> V1 var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C1 { void M() { System.Console.WriteLine(3); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source2); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document2 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From(source2, Encoding.UTF8), filePath: sourceFile.Path); var documentId = document2.Id; var project = document2.Project; solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // user edits the file: solution = solution.WithDocumentText(documentId, SourceText.From(source3, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); // EnC service queries for a document, but the source file on disk doesn't match the PDB // We don't report rude edits for out-of-sync documents: var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // since the document is out-of-sync we need to call update to determine whether we have changes to apply or not: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Equal(new[] { $"{project.Id} Warning ENC1005: {string.Format(FeaturesResources.DocumentIsOutOfSyncWithDebuggee, sourceFile.Path)}" }, InspectDiagnostics(emitDiagnostics)); // undo: solution = solution.WithDocumentText(documentId, SourceText.From(source1, Encoding.UTF8)); var currentDocument = solution.GetDocument(documentId); // save (note that this call will fail to match the content with the PDB since it uses the content prior to the actual file write) await debuggingSession.OnSourceFileUpdatedAsync(currentDocument); var (doc, state) = await debuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(documentId, currentDocument, CancellationToken.None); Assert.Null(doc); Assert.Equal(CommittedSolution.DocumentState.OutOfSync, state); sourceFile.WriteAllText(source1); Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); // the content actually hasn't changed: Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_AddedFileNotObservedBeforeDebuggingSessionStart() { // workspace: ------|----V0---------------|---------- // file system: --V0--|---------------------|---------- // F5 ^ ^F10 (no change) // file watcher observes the file var source1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(source1); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with no file var project = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)); solution = project.Solution; var moduleId = EmitAndLoadLibraryToDebuggee(source1, sourceFilePath: sourceFile.Path); _debuggerService.IsEditAndContinueAvailable = _ => new ManagedEditAndContinueAvailability(ManagedEditAndContinueAvailabilityStatus.Attach, localizedMessage: "*attached*"); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); // An active statement may be present in the added file since the file exists in the PDB: var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeSpan1 = GetSpan(source1, "System.Console.WriteLine(1);"); var sourceText1 = SourceText.From(source1, Encoding.UTF8); var activeLineSpan1 = sourceText1.Lines.GetLinePositionSpan(activeSpan1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, "test.cs", activeLineSpan1.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); // disallow any edits (attach scenario) EnterBreakState(debuggingSession, activeStatements); // File watcher observes the document and adds it to the workspace: var document1 = project.AddDocument("test.cs", sourceText1, filePath: sourceFile.Path); solution = document1.Project.Solution; // We don't report rude edits for the added document: var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics); // TODO: https://github.com/dotnet/roslyn/issues/49938 // We currently create the AS map against the committed solution, which may not contain all documents. // var spans = await service.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); // AssertEx.Equal(new[] { $"({activeLineSpan1}, IsLeafFrame)" }, spans.Single().Select(s => s.ToString())); // No changes. Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); AssertEx.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); } [Theory] [CombinatorialData] public async Task BreakMode_ValidSignificantChange_DocumentOutOfSync(bool delayLoad) { var sourceOnDisk = "class C1 { void M() { System.Console.WriteLine(1); } }"; var dir = Temp.CreateDirectory(); var sourceFile = dir.CreateFile("test.cs").WriteAllText(sourceOnDisk); using var _ = CreateWorkspace(out var solution, out var service); // the workspace starts with a version of the source that's not updated with the output of single file generator (or design-time build): var document1 = solution. AddProject("test", "test", LanguageNames.CSharp). AddMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Mscorlib40)). AddDocument("test.cs", SourceText.From("class C1 { void M() { System.Console.WriteLine(0); } }", Encoding.UTF8), filePath: sourceFile.Path); var project = document1.Project; solution = project.Solution; var moduleId = EmitLibrary(sourceOnDisk, sourceFilePath: sourceFile.Path); if (!delayLoad) { LoadLibraryToDebuggee(moduleId); } var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.None); EnterBreakState(debuggingSession); // no changes have been made to the project Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(updates.Updates); Assert.Empty(emitDiagnostics); // a file watcher observed a change and updated the document, so it now reflects the content on disk (the code that we compiled): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceOnDisk, Encoding.UTF8)); var document3 = solution.Projects.Single().Documents.Single(); var diagnostics = await service.GetDocumentDiagnosticsAsync(document3, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); // the content of the file is now exactly the same as the compiled document, so there is no change to be applied: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.None, updates.Status); Assert.Empty(emitDiagnostics); EndDebuggingSession(debuggingSession); Assert.Empty(debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); } [Theory] [CombinatorialData] public async Task ValidSignificantChange_EmitSuccessful(bool breakMode, bool commitUpdate) { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var sourceV2 = "class C1 { void M() { System.Console.WriteLine(2); } }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var moduleId = EmitAndLoadLibraryToDebuggee(sourceV1); var debuggingSession = await StartDebuggingSessionAsync(service, solution); if (breakMode) { EnterBreakState(debuggingSession); } // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); var diagnostics1 = await service.GetDocumentDiagnosticsAsync(document2, s_noActiveSpans, CancellationToken.None); AssertEx.Empty(diagnostics1); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); void ValidateDelta(ManagedModuleUpdate delta) { // check emitted delta: Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000001, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); } // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); AssertEx.Equal(updates.Updates, pendingUpdate.Deltas); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); if (commitUpdate) { // all update providers either provided updates or had no change to apply: CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, baselineReaders.Length); Assert.Same(readers[0], baselineReaders[0]); Assert.Same(readers[1], baselineReaders[1]); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: var commitedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.False(commitedUpdateSolutionStatus); } else { // another update provider blocked the update: debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // solution update status after committing an update: var discardedUpdateSolutionStatus = await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None); Assert.True(discardedUpdateSolutionStatus); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); ValidateDelta(updates.Updates.Single()); } if (breakMode) { ExitBreakState(); } EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); AssertEx.SetEqual(new[] { moduleId }, debuggingSession.GetTestAccessor().GetModulesPreparedForUpdate()); if (breakMode) { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount={(commitUpdate ? 2 : 1)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=True", }, _telemetryLog); } else { AssertEx.Equal(new[] { $"Debugging_EncSession: SessionId=1|SessionCount=0|EmptySessionCount=0|HotReloadSessionCount=1|EmptyHotReloadSessionCount={(commitUpdate ? 1 : 0)}", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=0|InBreakState=False" }, _telemetryLog); } } [Theory] [InlineData(true)] [InlineData(false)] public async Task BreakMode_ValidSignificantChange_EmitSuccessful_UpdateDeferred(bool commitUpdate) { var dir = Temp.CreateDirectory(); var sourceV1 = "class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilation(sourceV1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "lib"); var (peImage, pdbImage) = compilationV1.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadata = ModuleMetadata.CreateFromImage(peImage); var moduleFile = dir.CreateFile("lib.dll").WriteAllBytes(peImage); var pdbFile = dir.CreateFile("lib.pdb").WriteAllBytes(pdbImage); var moduleId = moduleMetadata.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new CompilationOutputFiles(moduleFile.Path, pdbFile.Path); // set up an active statement in the first method, so that we can test preservation of local signature. var activeStatements = ImmutableArray.Create(new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 0), documentName: document1.Name, sourceSpan: new SourceSpan(0, 15, 0, 16), ActiveStatementFlags.IsLeafFrame)); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module is not loaded: EnterBreakState(debuggingSession, activeStatements); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M1() { int a = 1; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var document2 = solution.GetDocument(document1.Id); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); // delta to apply: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(0x06000002, delta.UpdatedMethods.Single()); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); Assert.Equal(moduleId, delta.Module); Assert.Empty(delta.ExceptionRegions); Assert.Empty(delta.SequencePoints); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (baselineProjectId, newBaseline) = pendingUpdate.EmitBaselines.Single(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(2, readers.Length); Assert.NotNull(readers[0]); Assert.NotNull(readers[1]); Assert.Equal(document2.Project.Id, baselineProjectId); Assert.Equal(moduleId, newBaseline.OriginalMetadata.GetModuleVersionId()); if (commitUpdate) { CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added: Assert.Same(newBaseline, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(document2.Project.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); // make another update: EnterBreakState(debuggingSession); // Update M1 - this method has an active statement, so we will attempt to preserve the local signature. // Since the method hasn't been edited before we'll read the baseline PDB to get the signature token. // This validates that the Portable PDB reader can be used (and is not disposed) for a second generation edit. var document3 = solution.GetDocument(document1.Id); solution = solution.WithDocumentText(document3.Id, SourceText.From("class C1 { void M1() { int a = 3; System.Console.WriteLine(a); } void M2() { System.Console.WriteLine(2); } }", Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); } else { debuggingSession.DiscardSolutionUpdate(); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); } ExitBreakState(); EndDebuggingSession(debuggingSession); // open module readers should be disposed when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_PartialTypes() { var sourceA1 = @" partial class C { int X = 1; void F() { X = 1; } } partial class D { int U = 1; public D() { } } partial class D { int W = 1; } partial class E { int A; public E(int a) { A = a; } } "; var sourceB1 = @" partial class C { int Y = 1; } partial class E { int B; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; var sourceA2 = @" partial class C { int X = 2; void F() { X = 2; } } partial class D { int U = 2; } partial class D { int W = 2; public D() { } } partial class E { int A = 1; public E(int a) { A = a; } } "; var sourceB2 = @" partial class C { int Y = 2; } partial class E { int B = 2; public E(int a, int b) { A = a; B = new System.Func<int>(() => b)(); } } "; using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, new[] { sourceA1, sourceB1 }); var project = solution.Projects.Single(); LoadLibraryToDebuggee(EmitLibrary(new[] { (sourceA1, "test1.cs"), (sourceB1, "test2.cs") })); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): var documentA = project.Documents.First(); var documentB = project.Documents.Skip(1).First(); solution = solution.WithDocumentText(documentA.Id, SourceText.From(sourceA2, Encoding.UTF8)); solution = solution.WithDocumentText(documentB.Id, SourceText.From(sourceB2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(6, delta.UpdatedMethods.Length); // F, C.C(), D.D(), E.E(int), E.E(int, int), lambda AssertEx.SetEqual(new[] { 0x02000002, 0x02000003, 0x02000004, 0x02000005 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } private static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) => new(MetadataTokens.Handle(table, rowNumber), operation); private static unsafe void VerifyEncLogMetadata(ImmutableArray<byte> delta, params EditAndContinueLogEntry[] expectedRows) { fixed (byte* ptr = delta.ToArray()) { var reader = new MetadataReader(ptr, delta.Length); AssertEx.Equal(expectedRows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } } private static void GenerateSource(GeneratorExecutionContext context) { foreach (var syntaxTree in context.Compilation.SyntaxTrees) { var fileName = PathUtilities.GetFileName(syntaxTree.FilePath); Generate(syntaxTree.GetText().ToString(), fileName); if (context.AnalyzerConfigOptions.GetOptions(syntaxTree).TryGetValue("enc_generator_output", out var optionValue)) { context.AddSource("GeneratedFromOptions_" + fileName, $"class G {{ int X => {optionValue}; }}"); } } foreach (var additionalFile in context.AdditionalFiles) { Generate(additionalFile.GetText()!.ToString(), PathUtilities.GetFileName(additionalFile.Path)); } void Generate(string source, string fileName) { var generatedSource = GetGeneratedCodeFromMarkedSource(source); if (generatedSource != null) { context.AddSource($"Generated_{fileName}", generatedSource); } } } private static string GetGeneratedCodeFromMarkedSource(string markedSource) { const string OpeningMarker = "/* GENERATE:"; const string ClosingMarker = "*/"; var index = markedSource.IndexOf(OpeningMarker); if (index > 0) { index += OpeningMarker.Length; var closing = markedSource.IndexOf(ClosingMarker, index); return markedSource[index..closing].Trim(); } return null; } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate() { var sourceV1 = @" /* GENERATE: class G { int X => 1; } */ class C { int Y => 1; } "; var sourceV2 = @" /* GENERATE: class G { int X => 2; } */ class C { int Y => 2; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(2, delta.UpdatedMethods.Length); AssertEx.Equal(new[] { 0x02000002, 0x02000003 }, delta.UpdatedTypes, itemInspector: t => "0x" + t.ToString("X")); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentUpdate_LineChanges() { var sourceV1 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var sourceV2 = @" /* GENERATE: class G { int M() { return 1; } } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); var lineUpdate = delta.SequencePoints.Single(); AssertEx.Equal(new[] { "3 -> 4" }, lineUpdate.LineUpdates.Select(edit => $"{edit.OldLine} -> {edit.NewLine}")); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentUpdate_GeneratedDocumentInsert() { var sourceV1 = @" partial class C { int X = 1; } "; var sourceV2 = @" /* GENERATE: partial class C { int Y = 2; } */ partial class C { int X = 1; } "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1, generator); var moduleId = EmitLibrary(sourceV1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From(sourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); // constructor update Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AdditionalDocumentUpdate() { var source = @" class C { int Y => 1; } "; var additionalSourceV1 = @" /* GENERATE: class G { int X => 1; } */ "; var additionalSourceV2 = @" /* GENERATE: class G { int X => 2; } */ "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, additionalFileText: additionalSourceV1); var moduleId = EmitLibrary(source, generator: generator, additionalFileText: additionalSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var additionalDocument1 = solution.Projects.Single().AdditionalDocuments.Single(); solution = solution.WithAdditionalDocumentText(additionalDocument1.Id, SourceText.From(additionalSourceV2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_AnalyzerConfigUpdate() { var source = @" class C { int Y => 1; } "; var configV1 = new[] { ("enc_generator_output", "1") }; var configV2 = new[] { ("enc_generator_output", "2") }; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, source, generator, analyzerConfig: configV1); var moduleId = EmitLibrary(source, generator: generator, analyzerOptions: configV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // change the additional source (valid edit): var configDocument1 = solution.Projects.Single().AnalyzerConfigDocuments.Single(); solution = solution.WithAnalyzerConfigDocumentText(configDocument1.Id, GetAnalyzerConfigText(configV2)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000003, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } [Fact] public async Task BreakMode_ValidSignificantChange_SourceGenerators_DocumentRemove() { var source1 = ""; var generator = new TestSourceGenerator() { ExecuteImpl = context => context.AddSource("generated", $"class G {{ int X => {context.Compilation.SyntaxTrees.Count()}; }}") }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator); var moduleId = EmitLibrary(source1, generator: generator); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // remove the source document (valid edit): solution = document1.Project.Solution.RemoveDocument(document1.Id); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Equal(1, delta.UpdatedMethods.Length); Assert.Equal(0x02000002, delta.UpdatedTypes.Single()); EndDebuggingSession(debuggingSession); } /// <summary> /// Emulates two updates to Multi-TFM project. /// </summary> [Fact] public async Task TwoUpdatesWithLoadedAndUnloadedModule() { var dir = Temp.CreateDirectory(); var source1 = "class A { void M() { System.Console.WriteLine(1); } }"; var source2 = "class A { void M() { System.Console.WriteLine(2); } }"; var source3 = "class A { void M() { System.Console.WriteLine(3); } }"; var compilationA = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "A"); var compilationB = CSharpTestBase.CreateCompilation(source1, options: TestOptions.DebugDll, targetFramework: DefaultTargetFramework, assemblyName: "B"); var (peImageA, pdbImageA) = compilationA.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataA = ModuleMetadata.CreateFromImage(peImageA); var moduleFileA = Temp.CreateFile("A.dll").WriteAllBytes(peImageA); var pdbFileA = dir.CreateFile("A.pdb").WriteAllBytes(pdbImageA); var moduleIdA = moduleMetadataA.GetModuleVersionId(); var (peImageB, pdbImageB) = compilationB.EmitToArrays(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)); var moduleMetadataB = ModuleMetadata.CreateFromImage(peImageB); var moduleFileB = dir.CreateFile("B.dll").WriteAllBytes(peImageB); var pdbFileB = dir.CreateFile("B.pdb").WriteAllBytes(pdbImageB); var moduleIdB = moduleMetadataB.GetModuleVersionId(); using var _ = CreateWorkspace(out var solution, out var service); (solution, var documentA) = AddDefaultTestProject(solution, source1); var projectA = documentA.Project; var projectB = solution.AddProject("B", "A", "C#").AddMetadataReferences(projectA.MetadataReferences).AddDocument("DocB", source1, filePath: "DocB.cs").Project; solution = projectB.Solution; _mockCompilationOutputsProvider = project => (project.Id == projectA.Id) ? new CompilationOutputFiles(moduleFileA.Path, pdbFileA.Path) : (project.Id == projectB.Id) ? new CompilationOutputFiles(moduleFileB.Path, pdbFileB.Path) : throw ExceptionUtilities.UnexpectedValue(project); // only module A is loaded LoadLibraryToDebuggee(moduleIdA); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession); // // First update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); var deltaA = updates.Updates.Single(d => d.Module == moduleIdA); var deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: var pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB1) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); var baselineA0 = newBaselineA1.GetInitialEmitBaseline(); var baselineB0 = newBaselineB1.GetInitialEmitBaseline(); var readers = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); Assert.Equal(4, readers.Length); Assert.False(readers.Any(r => r is null)); Assert.Equal(moduleIdA, newBaselineA1.OriginalMetadata.GetModuleVersionId()); Assert.Equal(moduleIdB, newBaselineB1.OriginalMetadata.GetModuleVersionId()); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // verify that baseline is added for both modules: Assert.Same(newBaselineA1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB1, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EnterBreakState(debuggingSession); // // Second update. // solution = solution.WithDocumentText(projectA.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); solution = solution.WithDocumentText(projectB.Documents.Single().Id, SourceText.From(source3, Encoding.UTF8)); // validate solution update status and emit: Assert.True(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); Assert.Empty(emitDiagnostics); deltaA = updates.Updates.Single(d => d.Module == moduleIdA); deltaB = updates.Updates.Single(d => d.Module == moduleIdB); Assert.Equal(2, updates.Updates.Length); // the update should be stored on the service: pendingUpdate = debuggingSession.GetTestAccessor().GetPendingSolutionUpdate(); var (_, newBaselineA2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectA.Id); var (_, newBaselineB2) = pendingUpdate.EmitBaselines.Single(b => b.ProjectId == projectB.Id); Assert.NotSame(newBaselineA1, newBaselineA2); Assert.NotSame(newBaselineB1, newBaselineB2); Assert.Same(baselineA0, newBaselineA2.GetInitialEmitBaseline()); Assert.Same(baselineB0, newBaselineB2.GetInitialEmitBaseline()); Assert.Same(baselineA0.OriginalMetadata, newBaselineA2.OriginalMetadata); Assert.Same(baselineB0.OriginalMetadata, newBaselineB2.OriginalMetadata); // no new module readers: var baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); CommitSolutionUpdate(debuggingSession); Assert.Null(debuggingSession.GetTestAccessor().GetPendingSolutionUpdate()); // no change in non-remappable regions since we didn't have any active statements: Assert.Empty(debuggingSession.NonRemappableRegions); // module readers tracked: baselineReaders = debuggingSession.GetTestAccessor().GetBaselineModuleReaders(); AssertEx.Equal(readers, baselineReaders); // verify that baseline is updated for both modules: Assert.Same(newBaselineA2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectA.Id)); Assert.Same(newBaselineB2, debuggingSession.GetTestAccessor().GetProjectEmitBaseline(projectB.Id)); // solution update status after committing an update: Assert.False(await debuggingSession.EditSession.HasChangesAsync(solution, s_noActiveSpans, sourceFilePath: null, CancellationToken.None)); ExitBreakState(); EndDebuggingSession(debuggingSession); // open deferred module readers should be dispose when the debugging session ends: VerifyReadersDisposed(readers); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_NoStream() { using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, "class C1 { void M() { System.Console.WriteLine(1); } }"); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => null, OpenAssemblyStreamImpl = () => null, }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document1.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-pdb", new FileNotFoundException().Message)}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); } [Fact] public async Task BreakMode_ValidSignificantChange_BaselineCreationFailed_AssemblyReadError() { var sourceV1 = "class C1 { void M() { System.Console.WriteLine(1); } }"; var compilationV1 = CSharpTestBase.CreateCompilationWithMscorlib40(sourceV1, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = new MemoryStream(); var peImage = compilationV1.EmitToArray(new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb), pdbStream: pdbStream); pdbStream.Position = 0; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, sourceV1); _mockCompilationOutputsProvider = _ => new MockCompilationOutputs(Guid.NewGuid()) { OpenPdbStreamImpl = () => pdbStream, OpenAssemblyStreamImpl = () => throw new IOException("*message*"), }; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // module not loaded EnterBreakState(debuggingSession); // change the source (valid edit): var document1 = solution.Projects.Single().Documents.Single(); solution = solution.WithDocumentText(document1.Id, SourceText.From("class C1 { void M() { System.Console.WriteLine(2); } }", Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); AssertEx.Equal(new[] { $"{document.Project.Id} Error ENC1001: {string.Format(FeaturesResources.ErrorReadingFile, "test-assembly", "*message*")}" }, InspectDiagnostics(emitDiagnostics)); Assert.Equal(ManagedModuleUpdateStatus.Blocked, updates.Status); EndDebuggingSession(debuggingSession); AssertEx.Equal(new[] { "Debugging_EncSession: SessionId=1|SessionCount=1|EmptySessionCount=0|HotReloadSessionCount=0|EmptyHotReloadSessionCount=1", "Debugging_EncSession_EditSession: SessionId=1|EditSessionId=2|HadCompilationErrors=False|HadRudeEdits=False|HadValidChanges=True|HadValidInsignificantChanges=False|RudeEditsCount=0|EmitDeltaErrorIdCount=1|InBreakState=True", "Debugging_EncSession_EditSession_EmitDeltaErrorId: SessionId=1|EditSessionId=2|ErrorId=ENC1001" }, _telemetryLog); } [Fact] public async Task ActiveStatements() { var sourceV1 = "class C { void F() { G(1); } void G(int a) => System.Console.WriteLine(1); }"; var sourceV2 = "class C { int x; void F() { G(2); G(1); } void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1);"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var activeSpan21 = GetSpan(sourceV2, "G(2); G(1);"); var activeSpan22 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var adjustedActiveSpan1 = GetSpan(sourceV2, "G(2);"); var adjustedActiveSpan2 = GetSpan(sourceV2, "System.Console.WriteLine(2)"); var documentId = document1.Id; var documentPath = document1.FilePath; var sourceTextV1 = document1.GetTextSynchronously(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var activeLineSpan21 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan21); var activeLineSpan22 = sourceTextV2.Lines.GetLinePositionSpan(activeSpan22); var adjustedActiveLineSpan1 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan1); var adjustedActiveLineSpan2 = sourceTextV2.Lines.GetLinePositionSpan(adjustedActiveSpan2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); // default if not called in a break state Assert.True((await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None)).IsDefault); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentPath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentPath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var activeStatementSpan11 = new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan12 = new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document1.Id), CancellationToken.None); AssertEx.Equal(new[] { activeStatementSpan11, activeStatementSpan12 }, baseSpans.Single()); var trackedActiveSpans1 = ImmutableArray.Create(activeStatementSpan11, activeStatementSpan12); var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document1, (_, _, _) => new(trackedActiveSpans1), CancellationToken.None); AssertEx.Equal(trackedActiveSpans1, currentSpans); Assert.Equal(activeLineSpan11, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction1, CancellationToken.None)); Assert.Equal(activeLineSpan12, await debuggingSession.GetCurrentActiveStatementPositionAsync(document1.Project.Solution, (_, _, _) => new(trackedActiveSpans1), activeInstruction2, CancellationToken.None)); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // tracking span update triggered by the edit: var activeStatementSpan21 = new ActiveStatementSpan(0, activeLineSpan21, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null); var activeStatementSpan22 = new ActiveStatementSpan(1, activeLineSpan22, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null); var trackedActiveSpans2 = ImmutableArray.Create(activeStatementSpan21, activeStatementSpan22); currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => new(trackedActiveSpans2), CancellationToken.None); AssertEx.Equal(new[] { adjustedActiveLineSpan1, adjustedActiveLineSpan2 }, currentSpans.Select(s => s.LineSpan)); Assert.Equal(adjustedActiveLineSpan1, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction1, CancellationToken.None)); Assert.Equal(adjustedActiveLineSpan2, await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => new(trackedActiveSpans2), activeInstruction2, CancellationToken.None)); } [Theory] [CombinatorialData] public async Task ActiveStatements_SyntaxErrorOrOutOfSyncDocument(bool isOutOfSync) { var sourceV1 = "class C { void F() => G(1); void G(int a) => System.Console.WriteLine(1); }"; // syntax error (missing ';') unless testing out-of-sync document var sourceV2 = isOutOfSync ? "class C { int x; void F() => G(1); void G(int a) => System.Console.WriteLine(2); }" : "class C { int x void F() => G(1); void G(int a) => System.Console.WriteLine(2); }"; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, sourceV1); var activeSpan11 = GetSpan(sourceV1, "G(1)"); var activeSpan12 = GetSpan(sourceV1, "System.Console.WriteLine(1)"); var documentId = document1.Id; var documentFilePath = document1.FilePath; var sourceTextV1 = await document1.GetTextAsync(CancellationToken.None); var sourceTextV2 = SourceText.From(sourceV2, Encoding.UTF8); var activeLineSpan11 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan11); var activeLineSpan12 = sourceTextV1.Lines.GetLinePositionSpan(activeSpan12); var debuggingSession = await StartDebuggingSessionAsync( service, solution, isOutOfSync ? CommittedSolution.DocumentState.OutOfSync : CommittedSolution.DocumentState.MatchesBuildOutput); var moduleId = Guid.NewGuid(); var activeInstruction1 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000001, version: 1), ilOffset: 1); var activeInstruction2 = new ManagedInstructionId(new ManagedMethodId(moduleId, token: 0x06000002, version: 1), ilOffset: 1); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( activeInstruction1, documentFilePath, activeLineSpan11.ToSourceSpan(), ActiveStatementFlags.IsNonLeafFrame), new ManagedActiveStatementDebugInfo( activeInstruction2, documentFilePath, activeLineSpan12.ToSourceSpan(), ActiveStatementFlags.IsLeafFrame)); EnterBreakState(debuggingSession, activeStatements); var baseSpans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, activeLineSpan11, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null), new ActiveStatementSpan(1, activeLineSpan12, ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null) }, baseSpans); // change the source (valid edit): solution = solution.WithDocumentText(documentId, sourceTextV2); var document2 = solution.GetDocument(documentId); // no adjustments made due to syntax error or out-of-sync document: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document2, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), CancellationToken.None); AssertEx.Equal(new[] { activeLineSpan11, activeLineSpan12 }, currentSpans.Select(s => s.LineSpan)); var currentSpan1 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction1, CancellationToken.None); var currentSpan2 = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, (_, _, _) => ValueTaskFactory.FromResult(baseSpans), activeInstruction2, CancellationToken.None); if (isOutOfSync) { Assert.Equal(baseSpans[0].LineSpan, currentSpan1.Value); Assert.Equal(baseSpans[1].LineSpan, currentSpan2.Value); } else { Assert.Null(currentSpan1); Assert.Null(currentSpan2); } } [Fact] public async Task ActiveStatements_ForeignDocument() { var composition = FeaturesTestCompositions.Features.AddParts(typeof(DummyLanguageService)); using var _ = CreateWorkspace(out var solution, out var service, new[] { typeof(DummyLanguageService) }); var project = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); var document = project.AddDocument("test", SourceText.From("dummy1")); solution = document.Project.Solution; var debuggingSession = await StartDebuggingSessionAsync(service, solution); var activeStatements = ImmutableArray.Create( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(Guid.Empty, token: 0x06000001, version: 1), ilOffset: 0), documentName: document.Name, sourceSpan: new SourceSpan(0, 1, 0, 2), ActiveStatementFlags.IsNonLeafFrame)); EnterBreakState(debuggingSession, activeStatements); // active statements are not tracked in non-Roslyn projects: var currentSpans = await debuggingSession.GetAdjustedActiveStatementSpansAsync(document, s_noActiveSpans, CancellationToken.None); Assert.Empty(currentSpans); var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); Assert.Empty(baseSpans.Single()); } [Fact, WorkItem(24320, "https://github.com/dotnet/roslyn/issues/24320")] public async Task ActiveStatements_LinkedDocuments() { var markedSources = new[] { @"class Test1 { static void Main() => <AS:2>Project2::Test1.F();</AS:2> static void F() => <AS:1>Project4::Test2.M();</AS:1> }", @"class Test2 { static void M() => <AS:0>Console.WriteLine();</AS:0> }" }; var module1 = Guid.NewGuid(); var module2 = Guid.NewGuid(); var module4 = Guid.NewGuid(); var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 1 }, modules: new[] { module4, module2, module1 }); // Project1: Test1.cs, Test2.cs // Project2: Test1.cs (link from P1) // Project3: Test1.cs (link from P1) // Project4: Test2.cs (link from P1) using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var documents = solution.Projects.Single().Documents; var doc1 = documents.First(); var doc2 = documents.Skip(1).First(); var text1 = await doc1.GetTextAsync(); var text2 = await doc2.GetTextAsync(); DocumentId AddProjectAndLinkDocument(string projectName, Document doc, SourceText text) { var p = solution.AddProject(projectName, projectName, "C#"); var linkedDocId = DocumentId.CreateNewId(p.Id, projectName + "->" + doc.Name); solution = p.Solution.AddDocument(linkedDocId, doc.Name, text, filePath: doc.FilePath); return linkedDocId; } var docId3 = AddProjectAndLinkDocument("Project2", doc1, text1); var docId4 = AddProjectAndLinkDocument("Project3", doc1, text1); var docId5 = AddProjectAndLinkDocument("Project4", doc2, text2); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, debugInfos); // Base Active Statements var baseActiveStatementsMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); var documentMap = baseActiveStatementsMap.DocumentPathMap; Assert.Equal(2, documentMap.Count); AssertEx.Equal(new[] { $"2: {doc1.FilePath}: (2,32)-(2,52) flags=[MethodUpToDate, IsNonLeafFrame]", $"1: {doc1.FilePath}: (3,29)-(3,49) flags=[MethodUpToDate, IsNonLeafFrame]" }, documentMap[doc1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"0: {doc2.FilePath}: (0,39)-(0,59) flags=[IsLeafFrame, MethodUpToDate]", }, documentMap[doc2.FilePath].Select(InspectActiveStatement)); Assert.Equal(3, baseActiveStatementsMap.InstructionMap.Count); var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module4, s.InstructionId.Method.Module); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(module2, s.InstructionId.Method.Module); s = statements[2]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(module1, s.InstructionId.Method.Module); var spans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(doc1.Id, doc2.Id, docId3, docId4, docId5), CancellationToken.None); AssertEx.Equal(new[] { "(2,32)-(2,52), (3,29)-(3,49)", // test1.cs "(0,39)-(0,59)", // test2.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(2,32)-(2,52), (3,29)-(3,49)", // link test1.cs "(0,39)-(0,59)" // link test2.cs }, spans.Select(docSpans => string.Join(", ", docSpans.Select(span => span.LineSpan)))); } [Fact] public async Task ActiveStatements_OutOfSyncDocuments() { var markedSource1 = @"class C { static void M() { try { } catch (Exception e) { <AS:0>M();</AS:0> } } }"; var source2 = @"class C { static void M() { try { } catch (Exception e) { M(); } } }"; var markedSources = new[] { markedSource1 }; var thread1 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0 leaf) var debugInfos = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1 }, ilOffsets: new[] { 1 }, flags: new[] { ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var _ = CreateWorkspace(out var solution, out var service); solution = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSources)); var project = solution.Projects.Single(); var document = project.Documents.Single(); var debuggingSession = await StartDebuggingSessionAsync(service, solution, initialState: CommittedSolution.DocumentState.OutOfSync); EnterBreakState(debuggingSession, debugInfos); // update document to test a changed solution solution = solution.WithDocumentText(document.Id, SourceText.From(source2, Encoding.UTF8)); document = solution.GetDocument(document.Id); var baseActiveStatementMap = await debuggingSession.EditSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements - available in out-of-sync documents, as they reflect the state of the debuggee and not the base document content Assert.Single(baseActiveStatementMap.DocumentPathMap); AssertEx.Equal(new[] { $"0: {document.FilePath}: (9,18)-(9,22) flags=[IsLeafFrame, MethodUpToDate]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(1, baseActiveStatementMap.InstructionMap.Count); var activeStatement1 = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).Single(); Assert.Equal(0x06000001, activeStatement1.InstructionId.Method.Token); Assert.Equal(document.FilePath, activeStatement1.FilePath); Assert.True(activeStatement1.IsLeaf); // Active statement reported as unchanged as the containing document is out-of-sync: var baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(9,18)-(9,22)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); // Whether or not an active statement is in an exception region is unknown if the document is out-of-sync: Assert.Null(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); // Document got synchronized: debuggingSession.LastCommittedSolution.Test_SetDocumentState(document.Id, CommittedSolution.DocumentState.MatchesBuildOutput); // New location of the active statement reported: baseSpans = await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(document.Id), CancellationToken.None); AssertEx.Equal(new[] { $"(10,12)-(10,16)" }, baseSpans.Single().Select(s => s.LineSpan.ToString())); Assert.True(await debuggingSession.IsActiveStatementInExceptionRegionAsync(solution, activeStatement1.InstructionId, CancellationToken.None)); } [Fact] public async Task ActiveStatements_SourceGeneratedDocuments_LineDirectives() { var markedSource1 = @" /* GENERATE: class C { void F() { #line 1 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var markedSource2 = @" /* GENERATE: class C { void F() { #line 2 ""a.razor"" <AS:0>F();</AS:0> #line default } } */ "; var source1 = ActiveStatementsDescription.ClearTags(markedSource1); var source2 = ActiveStatementsDescription.ClearTags(markedSource2); var additionalFileSourceV1 = @" xxxxxxxxxxxxxxxxx "; var generator = new TestSourceGenerator() { ExecuteImpl = GenerateSource }; using var _ = CreateWorkspace(out var solution, out var service); (solution, var document1) = AddDefaultTestProject(solution, source1, generator, additionalFileText: additionalFileSourceV1); var generatedDocument1 = (await solution.Projects.Single().GetSourceGeneratedDocumentsAsync().ConfigureAwait(false)).Single(); var moduleId = EmitLibrary(source1, generator: generator, additionalFileText: additionalFileSourceV1); LoadLibraryToDebuggee(moduleId); var debuggingSession = await StartDebuggingSessionAsync(service, solution); EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { GetGeneratedCodeFromMarkedSource(markedSource1) }, filePaths: new[] { generatedDocument1.FilePath }, modules: new[] { moduleId }, methodRowIds: new[] { 1 }, methodVersions: new[] { 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame })); // change the source (valid edit) solution = solution.WithDocumentText(document1.Id, SourceText.From(source2, Encoding.UTF8)); // validate solution update status and emit: var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); // check emitted delta: var delta = updates.Updates.Single(); Assert.Empty(delta.ActiveStatements); Assert.NotEmpty(delta.ILDelta); Assert.NotEmpty(delta.MetadataDelta); Assert.NotEmpty(delta.PdbDelta); Assert.Empty(delta.UpdatedMethods); Assert.Empty(delta.UpdatedTypes); AssertEx.Equal(new[] { "a.razor: [0 -> 1]" }, delta.SequencePoints.Inspect()); EndDebuggingSession(debuggingSession); } /// <summary> /// Scenario: /// F5 a program that has function F that calls G. G has a long-running loop, which starts executing. /// The user makes following operations: /// 1) Break, edit F from version 1 to version 2, continue (change is applied), G is still running in its loop /// Function remapping is produced for F v1 -> F v2. /// 2) Hot-reload edit F (without breaking) to version 3. /// Function remapping is produced for F v2 -> F v3 based on the last set of active statements calculated for F v2. /// Assume that the execution did not progress since the last resume. /// These active statements will likely not match the actual runtime active statements, /// however F v2 will never be remapped since it was hot-reloaded and not EnC'd. /// This remapping is needed for mapping from F v1 to F v3. /// 3) Break. Update F to v4. /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakStateRemappingFollowedUpByRunStateUpdate() { var markedSourceV1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { /*insert1[1]*/B();/*insert2[5]*/B();/*insert3[10]*/B(); <AS:1>G();</AS:1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var markedSourceV4 = Update(markedSourceV3, marker: "3"); var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSourceV1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSourceV1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // EnC update F v1 -> v2 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); // Hot Reload update F v2 -> v3 solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV3), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=1", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); // EnC update F v3 -> v4 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSourceV1 }, // matches F v1 modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F - not up-to-date anymore })); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSourceV4), Encoding.UTF8)); (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // TODO: https://github.com/dotnet/roslyn/issues/52100 // this is incorrect. correct value is: 0x06000003 v1 | AS (9,14)-(9,18) δ=16 AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (9,14)-(9,18) δ=5" }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit, but not apply the edits /// - break /// </summary> [Fact] public async Task BreakInPresenceOfUnappliedChanges() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); <AS:1>G();</AS:1> } }"; var markedSource3 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { B(); B(); <AS:1>G();</AS:1> } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Update to snapshot 2, but don't apply solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); // EnC update F v2 -> v3 EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF1 = new LinePositionSpan(new LinePosition(8, 14), new LinePosition(8, 18)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span.Value); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource3), Encoding.UTF8)); // check that the active statement is mapped correctly to snapshot v3: var expectedSpanG2 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var expectedSpanF2 = new LinePositionSpan(new LinePosition(9, 14), new LinePosition(9, 18)); span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF2, span); spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, documentId), new ActiveStatementSpan(1, expectedSpanF2, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, documentId) }, spans); // no rude edits: var document1 = solution.GetDocument(documentId); var diagnostics = await service.GetDocumentDiagnosticsAsync(document1, s_noActiveSpans, CancellationToken.None); Assert.Empty(diagnostics); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); AssertEx.Equal(new[] { $"0x06000003 v1 | AS {document.FilePath}: (7,14)-(7,18) δ=2", }, InspectNonRemappableRegions(debuggingSession.NonRemappableRegions)); ExitBreakState(); } /// <summary> /// Scenario: /// - F5 /// - edit and apply edit that deletes non-leaf active statement /// - break /// </summary> [Fact, WorkItem(52100, "https://github.com/dotnet/roslyn/issues/52100")] public async Task BreakAfterRunModeChangeDeletesNonLeafActiveStatement() { var markedSource1 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { <AS:1>G();</AS:1> } }"; var markedSource2 = @"class Test { static bool B() => true; static void G() { while (B()); <AS:0>}</AS:0> static void F() { } }"; var moduleId = EmitAndLoadLibraryToDebuggee(ActiveStatementsDescription.ClearTags(markedSource1)); using var _ = CreateWorkspace(out var solution, out var service); (solution, var document) = AddDefaultTestProject(solution, ActiveStatementsDescription.ClearTags(markedSource1)); var documentId = document.Id; var debuggingSession = await StartDebuggingSessionAsync(service, solution); // Apply update: F v1 -> v2. solution = solution.WithDocumentText(documentId, SourceText.From(ActiveStatementsDescription.ClearTags(markedSource2), Encoding.UTF8)); var (updates, emitDiagnostics) = await EmitSolutionUpdateAsync(debuggingSession, solution); Assert.Empty(emitDiagnostics); Assert.Equal(0x06000003, updates.Updates.Single().UpdatedMethods.Single()); Assert.Equal(0x02000002, updates.Updates.Single().UpdatedTypes.Single()); Assert.Equal(ManagedModuleUpdateStatus.Ready, updates.Status); CommitSolutionUpdate(debuggingSession); // Break EnterBreakState(debuggingSession, GetActiveStatementDebugInfosCSharp( new[] { markedSource1 }, modules: new[] { moduleId, moduleId }, methodRowIds: new[] { 2, 3 }, methodVersions: new[] { 1, 1 }, // frame F v1 is still executing (G has not returned) flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // G ActiveStatementFlags.IsNonLeafFrame, // F })); // check that the active statement is mapped correctly to snapshot v2: var expectedSpanF1 = new LinePositionSpan(new LinePosition(7, 14), new LinePosition(7, 18)); var expectedSpanG1 = new LinePositionSpan(new LinePosition(3, 41), new LinePosition(3, 42)); var activeInstructionF1 = new ManagedInstructionId(new ManagedMethodId(moduleId, 0x06000003, version: 1), ilOffset: 0); var span = await debuggingSession.GetCurrentActiveStatementPositionAsync(solution, s_noActiveSpans, activeInstructionF1, CancellationToken.None); Assert.Equal(expectedSpanF1, span); var spans = (await debuggingSession.GetBaseActiveStatementSpansAsync(solution, ImmutableArray.Create(documentId), CancellationToken.None)).Single(); AssertEx.Equal(new[] { new ActiveStatementSpan(0, expectedSpanG1, ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, unmappedDocumentId: null), // TODO: https://github.com/dotnet/roslyn/issues/52100 // This is incorrect: the active statement shouldn't be reported since it has been deleted. // We need the debugger to mark the method version as replaced by run-mode update. new ActiveStatementSpan(1, expectedSpanF1, ActiveStatementFlags.IsNonLeafFrame, unmappedDocumentId: null) }, spans); ExitBreakState(); } [Fact] public async Task MultiSession() { var source1 = "class C { void M() { System.Console.WriteLine(); } }"; var source3 = "class C { void M() { WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var tasks = Enumerable.Range(0, 10).Select(async i => { var sessionId = await encService.StartDebuggingSessionAsync( solution, _debuggerService, captureMatchingDocuments: ImmutableArray<DocumentId>.Empty, captureAllMatchingDocuments: true, reportDiagnostics: true, CancellationToken.None); var solution1 = solution.WithDocumentText(documentIdA, SourceText.From("class C { void M() { System.Console.WriteLine(" + i + "); } }", Encoding.UTF8)); var result1 = await encService.EmitSolutionUpdateAsync(sessionId, solution1, s_noActiveSpans, CancellationToken.None); Assert.Empty(result1.Diagnostics); Assert.Equal(1, result1.ModuleUpdates.Updates.Length); var solution2 = solution1.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); var result2 = await encService.EmitSolutionUpdateAsync(sessionId, solution2, s_noActiveSpans, CancellationToken.None); Assert.Equal("CS0103", result2.Diagnostics.Single().Diagnostics.Single().Id); Assert.Empty(result2.ModuleUpdates.Updates); encService.EndDebuggingSession(sessionId, out var _); }); await Task.WhenAll(tasks); Assert.Empty(encService.GetTestAccessor().GetActiveDebuggingSessions()); } [Fact] public async Task WatchHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new WatchHotReloadService(workspace.Services, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition")); await hotReload.StartSessionAsync(solution, CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); AssertEx.Equal(new[] { 0x02000002 }, result.updates[0].UpdatedTypes); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public async Task UnitTestingHotReloadServiceTest() { var source1 = "class C { void M() { System.Console.WriteLine(1); } }"; var source2 = "class C { void M() { System.Console.WriteLine(2); } }"; var source3 = "class C { void X() { System.Console.WriteLine(2); } }"; var dir = Temp.CreateDirectory(); var sourceFileA = dir.CreateFile("A.cs").WriteAllText(source1); var moduleId = EmitLibrary(source1, sourceFileA.Path, Encoding.UTF8, "Proj"); using var workspace = CreateWorkspace(out var solution, out var encService); var projectP = solution. AddProject("P", "P", LanguageNames.CSharp). WithMetadataReferences(TargetFrameworkUtil.GetReferences(DefaultTargetFramework)); solution = projectP.Solution; var documentIdA = DocumentId.CreateNewId(projectP.Id, debugName: "A"); solution = solution.AddDocument(DocumentInfo.Create( id: documentIdA, name: "A", loader: new FileTextLoader(sourceFileA.Path, Encoding.UTF8), filePath: sourceFileA.Path)); var hotReload = new UnitTestingHotReloadService(workspace.Services); await hotReload.StartSessionAsync(solution, ImmutableArray.Create("Baseline", "AddDefinitionToExistingType", "NewTypeDefinition"), CancellationToken.None); var sessionId = hotReload.GetTestAccessor().SessionId; var session = encService.GetTestAccessor().GetDebuggingSession(sessionId); var matchingDocuments = session.LastCommittedSolution.Test_GetDocumentStates(); AssertEx.Equal(new[] { "(A, MatchesBuildOutput)" }, matchingDocuments.Select(e => (solution.GetDocument(e.id).Name, e.state)).OrderBy(e => e.Name).Select(e => e.ToString())); solution = solution.WithDocumentText(documentIdA, SourceText.From(source2, Encoding.UTF8)); var result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); Assert.Empty(result.diagnostics); Assert.Equal(1, result.updates.Length); solution = solution.WithDocumentText(documentIdA, SourceText.From(source3, Encoding.UTF8)); result = await hotReload.EmitSolutionUpdateAsync(solution, true, CancellationToken.None); AssertEx.Equal( new[] { "ENC0020: " + string.Format(FeaturesResources.Renaming_0_requires_restarting_the_application, FeaturesResources.method) }, result.diagnostics.Select(d => $"{d.Id}: {d.GetMessage()}")); Assert.Empty(result.updates); hotReload.EndSession(); } [Fact] public void ParseCapabilities() { var capabilities = ImmutableArray.Create("Baseline"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.False(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_CaseSensitive() { var capabilities = ImmutableArray.Create("BaseLine"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.False(service.HasFlag(EditAndContinueCapabilities.Baseline)); } [Fact] public void ParseCapabilities_IgnoreInvalid() { var capabilities = ImmutableArray.Create("Baseline", "Invalid", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_IgnoreInvalidNumeric() { var capabilities = ImmutableArray.Create("Baseline", "90", "NewTypeDefinition"); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); Assert.True(service.HasFlag(EditAndContinueCapabilities.Baseline)); Assert.True(service.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)); } [Fact] public void ParseCapabilities_AllCapabilitiesParsed() { foreach (var name in Enum.GetNames(typeof(EditAndContinueCapabilities))) { var capabilities = ImmutableArray.Create(name); var service = EditAndContinueWorkspaceService.ParseCapabilities(capabilities); var flag = (EditAndContinueCapabilities)Enum.Parse(typeof(EditAndContinueCapabilities), name); Assert.True(service.HasFlag(flag), $"Capability '{name}' was not parsed correctly, so it's impossible for a runtime to enable it!"); } } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Test/EditAndContinue/TraceLogTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class TraceLogTests { [Fact] public void Write() { var log = new TraceLog(5, "log"); var projectId = ProjectId.CreateFromSerialized(Guid.Parse("5E40F37C-5AB3-495E-A3F2-4A244D177674")); var diagnostic = Diagnostic.Create(EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile), Location.None, "file", "error"); log.Write("a"); log.Write("b {0} {1} {2}", 1, "x", 3); log.Write("c"); log.Write("d str={0} projectId={1} summary={2} diagnostic=`{3}`", (string)null, projectId, ProjectAnalysisSummary.RudeEdits, diagnostic); log.Write("e"); log.Write("f"); AssertEx.Equal(new[] { "f", "b 1 x 3", "c", $"d str=<null> projectId=1324595798 summary=RudeEdits diagnostic=`{diagnostic.ToString()}`", "e" }, log.GetTestAccessor().Entries.Select(e => e.GetDebuggerDisplay())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { public class TraceLogTests { [Fact] public void Write() { var log = new TraceLog(5, "log"); var projectId = ProjectId.CreateFromSerialized(Guid.Parse("5E40F37C-5AB3-495E-A3F2-4A244D177674"), debugName: "MyProject"); var diagnostic = Diagnostic.Create(EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile), Location.None, "file", "error"); log.Write("a"); log.Write("b {0} {1} {2}", 1, "x", 3); log.Write("c"); log.Write("d str={0} projectId={1} summary={2} diagnostic=`{3}`", (string)null, projectId, ProjectAnalysisSummary.RudeEdits, diagnostic); log.Write("e"); log.Write("f"); AssertEx.Equal(new[] { "f", "b 1 x 3", "c", $"d str=<null> projectId=MyProject summary=RudeEdits diagnostic=`{diagnostic}`", "e" }, log.GetTestAccessor().Entries.Select(e => e.GetDebuggerDisplay())); } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/DebuggingSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even whne it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry; private readonly EditSessionTelemetry _editSessionTelemetry; private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _telemetry = new DebuggingSessionTelemetry(); _editSessionTelemetry = new EditSessionTelemetry(); _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { _cancellationSource.Cancel(); // Consider: Some APIs on DebuggingSession (GetDocumentDiagnostics, OnSourceFileUpdated, GetXxxSpansAsync) can be called at any point in time. // These APIs should not be using the readers being disposed here, but there is no guarantee. Consider refactoring that would guarantee correctness. foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _cancellationSource.Dispose(); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); internal void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } internal PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); // TODO: report a separate telemetry data for hot reload sessions to preserve the semantics of the current telemetry data // https://github.com/dotnet/roslyn/issues/52128 if (EditSession.InBreakState) { _telemetry.LogEditSession(editSessionTelemetryData); } } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); internal bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } public void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> public async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } public bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> public bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline) { lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() => _ = RetrievePendingUpdate(); public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return ImmutableArray<ActiveStatementSpan>.Empty; } if (!mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Length; map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Represents a debugging session. /// </summary> internal sealed class DebuggingSession : IDisposable { private readonly Func<Project, CompilationOutputs> _compilationOutputsProvider; private readonly CancellationTokenSource _cancellationSource = new(); /// <summary> /// MVIDs read from the assembly built for given project id. /// </summary> private readonly Dictionary<ProjectId, (Guid Mvid, Diagnostic Error)> _projectModuleIds = new(); private readonly Dictionary<Guid, ProjectId> _moduleIds = new(); private readonly object _projectModuleIdsGuard = new(); /// <summary> /// The current baseline for given project id. /// The baseline is updated when changes are committed at the end of edit session. /// The backing module readers of initial baselines need to be kept alive -- store them in /// <see cref="_initialBaselineModuleReaders"/> and dispose them at the end of the debugging session. /// </summary> /// <remarks> /// The baseline of each updated project is linked to its initial baseline that reads from the on-disk metadata and PDB. /// Therefore once an initial baseline is created it needs to be kept alive till the end of the debugging session, /// even whne it's replaced in <see cref="_projectEmitBaselines"/> by a newer baseline. /// </remarks> private readonly Dictionary<ProjectId, EmitBaseline> _projectEmitBaselines = new(); private readonly List<IDisposable> _initialBaselineModuleReaders = new(); private readonly object _projectEmitBaselinesGuard = new(); // Maps active statement instructions reported by the debugger to their latest spans that might not yet have been applied // (remapping not triggered yet). Consumed by the next edit session and updated when changes are committed at the end of the edit session. // // Consider a function F containing a call to function G. While G is being executed, F is updated a couple of times (in two edit sessions) // before the thread returns from G and is remapped to the latest version of F. At the start of the second edit session, // the active instruction reported by the debugger is still at the original location since function F has not been remapped yet (G has not returned yet). // // '>' indicates an active statement instruction for non-leaf frame reported by the debugger. // v1 - before first edit, G executing // v2 - after first edit, G still executing // v3 - after second edit and G returned // // F v1: F v2: F v3: // 0: nop 0: nop 0: nop // 1> G() 1> nop 1: nop // 2: nop 2: G() 2: nop // 3: nop 3: nop 3> G() // // When entering a break state we query the debugger for current active statements. // The returned statements reflect the current state of the threads in the runtime. // When a change is successfully applied we remember changes in active statement spans. // These changes are passed to the next edit session. // We use them to map the spans for active statements returned by the debugger. // // In the above case the sequence of events is // 1st break: get active statements returns (F, v=1, il=1, span1) the active statement is up-to-date // 1st apply: detected span change for active statement (F, v=1, il=1): span1->span2 // 2nd break: previously updated statements contains (F, v=1, il=1)->span2 // get active statements returns (F, v=1, il=1, span1) which is mapped to (F, v=1, il=1, span2) using previously updated statements // 2nd apply: detected span change for active statement (F, v=1, il=1): span2->span3 // 3rd break: previously updated statements contains (F, v=1, il=1)->span3 // get active statements returns (F, v=3, il=3, span3) the active statement is up-to-date // internal ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> NonRemappableRegions { get; private set; } internal EditSession EditSession { get; private set; } private readonly HashSet<Guid> _modulesPreparedForUpdate = new(); private readonly object _modulesPreparedForUpdateGuard = new(); internal readonly DebuggingSessionId Id; /// <summary> /// The solution captured when the debugging session entered run mode (application debugging started), /// or the solution which the last changes committed to the debuggee at the end of edit session were calculated from. /// The solution reflecting the current state of the modules loaded in the debugee. /// </summary> internal readonly CommittedSolution LastCommittedSolution; internal readonly IManagedEditAndContinueDebuggerService DebuggerService; /// <summary> /// Gets the capabilities of the runtime with respect to applying code changes. /// </summary> internal readonly EditAndContinueCapabilities Capabilities; /// <summary> /// True if the diagnostics produced by the session should be reported to the diagnotic analyzer. /// </summary> internal readonly bool ReportDiagnostics; private readonly DebuggingSessionTelemetry _telemetry; private readonly EditSessionTelemetry _editSessionTelemetry; private PendingSolutionUpdate? _pendingUpdate; private Action<DebuggingSessionTelemetry.Data> _reportTelemetry; #pragma warning disable IDE0052 // Remove unread private members /// <summary> /// Last array of module updates generated during the debugging session. /// Useful for crash dump diagnostics. /// </summary> private ImmutableArray<ManagedModuleUpdate> _lastModuleUpdatesLog; #pragma warning restore internal DebuggingSession( DebuggingSessionId id, Solution solution, IManagedEditAndContinueDebuggerService debuggerService, EditAndContinueCapabilities capabilities, Func<Project, CompilationOutputs> compilationOutputsProvider, IEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>> initialDocumentStates, bool reportDiagnostics) { _compilationOutputsProvider = compilationOutputsProvider; _telemetry = new DebuggingSessionTelemetry(); _editSessionTelemetry = new EditSessionTelemetry(); _reportTelemetry = ReportTelemetry; Id = id; Capabilities = capabilities; DebuggerService = debuggerService; LastCommittedSolution = new CommittedSolution(this, solution, initialDocumentStates); NonRemappableRegions = ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty; EditSession = new EditSession(this, _editSessionTelemetry, inBreakState: false); ReportDiagnostics = reportDiagnostics; } public void Dispose() { _cancellationSource.Cancel(); // Consider: Some APIs on DebuggingSession (GetDocumentDiagnostics, OnSourceFileUpdated, GetXxxSpansAsync) can be called at any point in time. // These APIs should not be using the readers being disposed here, but there is no guarantee. Consider refactoring that would guarantee correctness. foreach (var reader in GetBaselineModuleReaders()) { reader.Dispose(); } _cancellationSource.Dispose(); } internal Task OnSourceFileUpdatedAsync(Document document) => LastCommittedSolution.OnSourceFileUpdatedAsync(document, _cancellationSource.Token); internal void StorePendingUpdate(Solution solution, SolutionUpdate update) { var previousPendingUpdate = Interlocked.Exchange(ref _pendingUpdate, new PendingSolutionUpdate( solution, update.EmitBaselines, update.ModuleUpdates.Updates, update.NonRemappableRegions)); // commit/discard was not called: Contract.ThrowIfFalse(previousPendingUpdate == null); } internal PendingSolutionUpdate RetrievePendingUpdate() { var pendingUpdate = Interlocked.Exchange(ref _pendingUpdate, null); Contract.ThrowIfNull(pendingUpdate); return pendingUpdate; } private void EndEditSession(out ImmutableArray<DocumentId> documentsToReanalyze) { documentsToReanalyze = EditSession.GetDocumentsWithReportedDiagnostics(); var editSessionTelemetryData = EditSession.Telemetry.GetDataAndClear(); _telemetry.LogEditSession(editSessionTelemetryData); } public void EndSession(out ImmutableArray<DocumentId> documentsToReanalyze, out DebuggingSessionTelemetry.Data telemetryData) { EndEditSession(out documentsToReanalyze); telemetryData = _telemetry.GetDataAndClear(); _reportTelemetry(telemetryData); Dispose(); } public void BreakStateEntered(out ImmutableArray<DocumentId> documentsToReanalyze) => RestartEditSession(inBreakState: true, out documentsToReanalyze); internal void RestartEditSession(bool inBreakState, out ImmutableArray<DocumentId> documentsToReanalyze) { EndEditSession(out documentsToReanalyze); EditSession = new EditSession(this, EditSession.Telemetry, inBreakState); } private ImmutableArray<IDisposable> GetBaselineModuleReaders() { lock (_projectEmitBaselinesGuard) { return _initialBaselineModuleReaders.ToImmutableArrayOrEmpty(); } } internal CompilationOutputs GetCompilationOutputs(Project project) => _compilationOutputsProvider(project); internal bool AddModulePreparedForUpdate(Guid mvid) { lock (_modulesPreparedForUpdateGuard) { return _modulesPreparedForUpdate.Add(mvid); } } public void CommitSolutionUpdate(PendingSolutionUpdate update) { // Save new non-remappable regions for the next edit session. // If no edits were made the pending list will be empty and we need to keep the previous regions. var nonRemappableRegions = GroupToImmutableDictionary( from moduleRegions in update.NonRemappableRegions from region in moduleRegions.Regions group region.Region by new ManagedMethodId(moduleRegions.ModuleId, region.Method)); if (nonRemappableRegions.Count > 0) { NonRemappableRegions = nonRemappableRegions; } // update baselines: lock (_projectEmitBaselinesGuard) { foreach (var (projectId, baseline) in update.EmitBaselines) { _projectEmitBaselines[projectId] = baseline; } } LastCommittedSolution.CommitSolution(update.Solution); } /// <summary> /// Reads the MVID of a compiled project. /// </summary> /// <returns> /// An MVID and an error message to report, in case an IO exception occurred while reading the binary. /// The MVID is default if either project not built, or an it can't be read from the module binary. /// </returns> public async Task<(Guid Mvid, Diagnostic? Error)> GetProjectModuleIdAsync(Project project, CancellationToken cancellationToken) { lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } } (Guid Mvid, Diagnostic? Error) ReadMvid() { var outputs = GetCompilationOutputs(project); try { return (outputs.ReadAssemblyModuleVersionId(), Error: null); } catch (Exception e) when (e is FileNotFoundException or DirectoryNotFoundException) { return (Mvid: Guid.Empty, Error: null); } catch (Exception e) { var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); return (Mvid: Guid.Empty, Error: Diagnostic.Create(descriptor, Location.None, new[] { outputs.AssemblyDisplayPath, e.Message })); } } var newId = await Task.Run(ReadMvid, cancellationToken).ConfigureAwait(false); lock (_projectModuleIdsGuard) { if (_projectModuleIds.TryGetValue(project.Id, out var id)) { return id; } _moduleIds[newId.Mvid] = project.Id; return _projectModuleIds[project.Id] = newId; } } public bool TryGetProjectId(Guid moduleId, [NotNullWhen(true)] out ProjectId? projectId) { lock (_projectModuleIdsGuard) { return _moduleIds.TryGetValue(moduleId, out projectId); } } /// <summary> /// Get <see cref="EmitBaseline"/> for given project. /// </summary> /// <returns>True unless the project outputs can't be read.</returns> public bool TryGetOrCreateEmitBaseline(Project project, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline) { lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { diagnostics = ImmutableArray<Diagnostic>.Empty; return true; } } var outputs = GetCompilationOutputs(project); if (!TryCreateInitialBaseline(outputs, project.Id, out diagnostics, out var newBaseline, out var debugInfoReaderProvider, out var metadataReaderProvider)) { // Unable to read the DLL/PDB at this point (it might be open by another process). // Don't cache the failure so that the user can attempt to apply changes again. return false; } lock (_projectEmitBaselinesGuard) { if (_projectEmitBaselines.TryGetValue(project.Id, out baseline)) { metadataReaderProvider.Dispose(); debugInfoReaderProvider.Dispose(); return true; } _projectEmitBaselines[project.Id] = newBaseline; _initialBaselineModuleReaders.Add(metadataReaderProvider); _initialBaselineModuleReaders.Add(debugInfoReaderProvider); } baseline = newBaseline; return true; } private static unsafe bool TryCreateInitialBaseline( CompilationOutputs compilationOutputs, ProjectId projectId, out ImmutableArray<Diagnostic> diagnostics, [NotNullWhen(true)] out EmitBaseline? baseline, [NotNullWhen(true)] out DebugInformationReaderProvider? debugInfoReaderProvider, [NotNullWhen(true)] out MetadataReaderProvider? metadataReaderProvider) { // Read the metadata and symbols from the disk. Close the files as soon as we are done emitting the delta to minimize // the time when they are being locked. Since we need to use the baseline that is produced by delta emit for the subsequent // delta emit we need to keep the module metadata and symbol info backing the symbols of the baseline alive in memory. // Alternatively, we could drop the data once we are done with emitting the delta and re-emit the baseline again // when we need it next time and the module is loaded. diagnostics = default; baseline = null; debugInfoReaderProvider = null; metadataReaderProvider = null; var success = false; var fileBeingRead = compilationOutputs.PdbDisplayPath; try { debugInfoReaderProvider = compilationOutputs.OpenPdb(); if (debugInfoReaderProvider == null) { throw new FileNotFoundException(); } var debugInfoReader = debugInfoReaderProvider.CreateEditAndContinueMethodDebugInfoReader(); fileBeingRead = compilationOutputs.AssemblyDisplayPath; metadataReaderProvider = compilationOutputs.OpenAssemblyMetadata(prefetch: true); if (metadataReaderProvider == null) { throw new FileNotFoundException(); } var metadataReader = metadataReaderProvider.GetMetadataReader(); var moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)metadataReader.MetadataPointer, metadataReader.MetadataLength); baseline = EmitBaseline.CreateInitialBaseline( moduleMetadata, debugInfoReader.GetDebugInfo, debugInfoReader.GetLocalSignature, debugInfoReader.IsPortable); success = true; return true; } catch (Exception e) { EditAndContinueWorkspaceService.Log.Write("Failed to create baseline for '{0}': {1}", projectId, e.Message); var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor(EditAndContinueErrorCode.ErrorReadingFile); diagnostics = ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { fileBeingRead, e.Message })); } finally { if (!success) { debugInfoReaderProvider?.Dispose(); metadataReaderProvider?.Dispose(); } } return false; } private static ImmutableDictionary<K, ImmutableArray<V>> GroupToImmutableDictionary<K, V>(IEnumerable<IGrouping<K, V>> items) where K : notnull { var builder = ImmutableDictionary.CreateBuilder<K, ImmutableArray<V>>(); foreach (var item in items) { builder.Add(item.Key, item.ToImmutableArray()); } return builder.ToImmutable(); } public async ValueTask<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { try { // Not a C# or VB project. var project = document.Project; if (!project.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Document does not compile to the assembly (e.g. cshtml files, .g.cs files generated for completion only) if (!document.DocumentState.SupportsEditAndContinue()) { return ImmutableArray<Diagnostic>.Empty; } // Do not analyze documents (and report diagnostics) of projects that have not been built. // Allow user to make any changes in these documents, they won't be applied within the current debugging session. // Do not report the file read error - it might be an intermittent issue. The error will be reported when the // change is attempted to be applied. var (mvid, _) = await GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvid == Guid.Empty) { return ImmutableArray<Diagnostic>.Empty; } var (oldDocument, oldDocumentState) = await LastCommittedSolution.GetDocumentAndStateAsync(document.Id, document, cancellationToken).ConfigureAwait(false); if (oldDocumentState is CommittedSolution.DocumentState.OutOfSync or CommittedSolution.DocumentState.Indeterminate or CommittedSolution.DocumentState.DesignTimeOnly) { // Do not report diagnostics for existing out-of-sync documents or design-time-only documents. return ImmutableArray<Diagnostic>.Empty; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, document, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (analysis.HasChanges) { // Once we detected a change in a document let the debugger know that the corresponding loaded module // is about to be updated, so that it can start initializing it for EnC update, reducing the amount of time applying // the change blocks the UI when the user "continues". if (AddModulePreparedForUpdate(mvid)) { // fire and forget: _ = Task.Run(() => DebuggerService.PrepareModuleForUpdateAsync(mvid, cancellationToken), cancellationToken); } } if (analysis.RudeEditErrors.IsEmpty) { return ImmutableArray<Diagnostic>.Empty; } EditSession.Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); // track the document, so that we can refresh or clean diagnostics at the end of edit session: EditSession.TrackDocumentWithReportedDiagnostics(document.Id); var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return analysis.RudeEditErrors.SelectAsArray((e, t) => e.ToDiagnostic(t), tree); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ImmutableArray<Diagnostic>.Empty; } } public async ValueTask<EmitSolutionUpdateResults> EmitSolutionUpdateAsync( Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { var solutionUpdate = await EditSession.EmitSolutionUpdateAsync(solution, activeStatementSpanProvider, cancellationToken).ConfigureAwait(false); LogSolutionUpdate(solutionUpdate); if (solutionUpdate.ModuleUpdates.Status == ManagedModuleUpdateStatus.Ready) { StorePendingUpdate(solution, solutionUpdate); } // Note that we may return empty deltas if all updates have been deferred. // The debugger will still call commit or discard on the update batch. return new EmitSolutionUpdateResults(solutionUpdate.ModuleUpdates, solutionUpdate.Diagnostics, solutionUpdate.DocumentsWithRudeEdits); } private void LogSolutionUpdate(SolutionUpdate update) { EditAndContinueWorkspaceService.Log.Write("Solution update status: {0}", ((int)update.ModuleUpdates.Status, typeof(ManagedModuleUpdateStatus))); if (update.ModuleUpdates.Updates.Length > 0) { var firstUpdate = update.ModuleUpdates.Updates[0]; EditAndContinueWorkspaceService.Log.Write("Solution update deltas: #{0} [types: #{1} (0x{2}:X8), methods: #{3} (0x{4}:X8)", update.ModuleUpdates.Updates.Length, firstUpdate.UpdatedTypes.Length, firstUpdate.UpdatedTypes.FirstOrDefault(), firstUpdate.UpdatedMethods.Length, firstUpdate.UpdatedMethods.FirstOrDefault()); } if (update.Diagnostics.Length > 0) { var firstProjectDiagnostic = update.Diagnostics[0]; EditAndContinueWorkspaceService.Log.Write("Solution update diagnostics: #{0} [{1}: {2}, ...]", update.Diagnostics.Length, firstProjectDiagnostic.ProjectId, firstProjectDiagnostic.Diagnostics[0]); } if (update.DocumentsWithRudeEdits.Length > 0) { var firstDocumentWithRudeEdits = update.DocumentsWithRudeEdits[0]; EditAndContinueWorkspaceService.Log.Write("Solution update documents with rude edits: #{0} [{1}: {2}, ...]", update.DocumentsWithRudeEdits.Length, firstDocumentWithRudeEdits.DocumentId, firstDocumentWithRudeEdits.Diagnostics[0].Kind); } _lastModuleUpdatesLog = update.ModuleUpdates.Updates; } public void CommitSolutionUpdate(out ImmutableArray<DocumentId> documentsToReanalyze) { var pendingUpdate = RetrievePendingUpdate(); CommitSolutionUpdate(pendingUpdate); // restart edit session with no active statements (switching to run mode): RestartEditSession(inBreakState: false, out documentsToReanalyze); } public void DiscardSolutionUpdate() => _ = RetrievePendingUpdate(); public async ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return default; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); using var _1 = PooledDictionary<string, ArrayBuilder<(ProjectId, int)>>.GetInstance(out var documentIndicesByMappedPath); using var _2 = PooledHashSet<ProjectId>.GetInstance(out var projectIds); // Construct map of mapped file path to a text document in the current solution // and a set of projects these documents are contained in. for (var i = 0; i < documentIds.Length; i++) { var documentId = documentIds[i]; var document = await solution.GetTextDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); if (document?.FilePath == null) { // document has been deleted or has no path (can't have an active statement anymore): continue; } // Multiple documents may have the same path (linked file). // The documents represent the files that #line directives map to. // Documents that have the same path must have different project id. documentIndicesByMappedPath.MultiAdd(document.FilePath, (documentId.ProjectId, i)); projectIds.Add(documentId.ProjectId); } using var _3 = PooledDictionary<ActiveStatement, ArrayBuilder<(DocumentId unmappedDocumentId, LinePositionSpan span)>>.GetInstance( out var activeStatementsInChangedDocuments); // Analyze changed documents in projects containing active statements: foreach (var projectId in projectIds) { var newProject = solution.GetRequiredProject(projectId); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = await solution.GetRequiredDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. continue; } var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); var analysis = await analyzer.AnalyzeDocumentAsync( LastCommittedSolution.GetRequiredProject(documentId.ProjectId), baseActiveStatements, newDocument, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { for (var i = 0; i < oldDocumentActiveStatements.Length; i++) { // Note: It is possible that one active statement appears in multiple documents if the documents represent a linked file. // Example (old and new contents): // #if Condition #if Condition // #line 1 a.txt #line 1 a.txt // [|F(1);|] [|F(1000);|] // #else #else // #line 1 a.txt #line 1 a.txt // [|F(2);|] [|F(2);|] // #endif #endif // // In the new solution the AS spans are different depending on which document view of the same file we are looking at. // Different views correspond to different projects. activeStatementsInChangedDocuments.MultiAdd(oldDocumentActiveStatements[i].Statement, (analysis.DocumentId, analysis.ActiveStatements[i].Span)); } } } } using var _4 = ArrayBuilder<ImmutableArray<ActiveStatementSpan>>.GetInstance(out var spans); spans.AddMany(ImmutableArray<ActiveStatementSpan>.Empty, documentIds.Length); foreach (var (mappedPath, documentBaseActiveStatements) in baseActiveStatements.DocumentPathMap) { if (documentIndicesByMappedPath.TryGetValue(mappedPath, out var indices)) { // translate active statements from base solution to the new solution, if the documents they are contained in changed: foreach (var (projectId, index) in indices) { spans[index] = documentBaseActiveStatements.SelectAsArray( activeStatement => { LinePositionSpan span; DocumentId? unmappedDocumentId; if (activeStatementsInChangedDocuments.TryGetValue(activeStatement, out var newSpans)) { (unmappedDocumentId, span) = newSpans.Single(ns => ns.unmappedDocumentId.ProjectId == projectId); } else { span = activeStatement.Span; unmappedDocumentId = null; } return new ActiveStatementSpan(activeStatement.Ordinal, span, activeStatement.Flags, unmappedDocumentId); }); } } } documentIndicesByMappedPath.FreeValues(); activeStatementsInChangedDocuments.FreeValues(); return spans.ToImmutable(); } public async ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(TextDocument mappedDocument, ActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken) { if (!EditSession.InBreakState) { return ImmutableArray<ActiveStatementSpan>.Empty; } if (!mappedDocument.State.SupportsEditAndContinue()) { return ImmutableArray<ActiveStatementSpan>.Empty; } Contract.ThrowIfNull(mappedDocument.FilePath); var newProject = mappedDocument.Project; var newSolution = newProject.Solution; var oldProject = LastCommittedSolution.GetProject(newProject.Id); if (oldProject == null) { // project has been added, no changes in active statement spans: return ImmutableArray<ActiveStatementSpan>.Empty; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.DocumentPathMap.TryGetValue(mappedDocument.FilePath, out var oldMappedDocumentActiveStatements)) { // no active statements in this document return ImmutableArray<ActiveStatementSpan>.Empty; } var newDocumentActiveStatementSpans = await activeStatementSpanProvider(mappedDocument.Id, mappedDocument.FilePath, cancellationToken).ConfigureAwait(false); if (newDocumentActiveStatementSpans.IsEmpty) { return ImmutableArray<ActiveStatementSpan>.Empty; } var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); using var _ = ArrayBuilder<ActiveStatementSpan>.GetInstance(out var adjustedMappedSpans); // Start with the current locations of the tracking spans. adjustedMappedSpans.AddRange(newDocumentActiveStatementSpans); // Update tracking spans to the latest known locations of the active statements contained in changed documents based on their analysis. await foreach (var unmappedDocumentId in EditSession.GetChangedDocumentsAsync(LastCommittedSolution, newProject, cancellationToken).ConfigureAwait(false)) { var newUnmappedDocument = await newSolution.GetRequiredDocumentAsync(unmappedDocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var (oldUnmappedDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newUnmappedDocument.Id, newUnmappedDocument, cancellationToken).ConfigureAwait(false); if (oldUnmappedDocument == null) { // document out-of-date continue; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldUnmappedDocument, newUnmappedDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); // Document content did not change or unable to determine active statement spans in a document with syntax errors: if (!analysis.ActiveStatements.IsDefault) { foreach (var activeStatement in analysis.ActiveStatements) { var i = adjustedMappedSpans.FindIndex((s, ordinal) => s.Ordinal == ordinal, activeStatement.Ordinal); if (i >= 0) { adjustedMappedSpans[i] = new ActiveStatementSpan(activeStatement.Ordinal, activeStatement.Span, activeStatement.Flags, unmappedDocumentId); } } } } return adjustedMappedSpans.ToImmutable(); } public async ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, ActiveStatementSpanProvider activeStatementSpanProvider, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { // It is allowed to call this method before entering or after exiting break mode. In fact, the VS debugger does so. // We return null since there the concept of active statement only makes sense during break mode. if (!EditSession.InBreakState) { return null; } var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // Active statement not found in any changed documents, return its last position: return baseActiveStatement.Span; } var newDocument = await solution.GetDocumentAsync(documentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (newDocument == null) { // The document has been deleted. return null; } var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // document out-of-date return null; } var analysis = await EditSession.Analyses.GetDocumentAnalysisAsync(LastCommittedSolution, oldDocument, newDocument, activeStatementSpanProvider, Capabilities, cancellationToken).ConfigureAwait(false); if (!analysis.HasChanges) { // Document content did not change: return baseActiveStatement.Span; } if (analysis.HasSyntaxErrors) { // Unable to determine active statement spans in a document with syntax errors: return null; } Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); return analysis.ActiveStatements.GetStatement(baseActiveStatement.Ordinal).Span; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } /// <summary> /// Called by the debugger to determine whether a non-leaf active statement is in an exception region, /// so it can determine whether the active statement can be remapped. This only happens when the EnC is about to apply changes. /// If the debugger determines we can remap active statements, the application of changes proceeds. /// /// TODO: remove (https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1310859) /// </summary> /// <returns> /// True if the instruction is located within an exception region, false if it is not, null if the instruction isn't an active statement in a changed method /// or the exception regions can't be determined. /// </returns> public async ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ManagedInstructionId instructionId, CancellationToken cancellationToken) { try { if (!EditSession.InBreakState) { return null; } // This method is only called when the EnC is about to apply changes, at which point all active statements and // their exception regions will be needed. Hence it's not necessary to scope this query down to just the instruction // the debugger is interested at this point while not calculating the others. var baseActiveStatements = await EditSession.BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); if (!baseActiveStatements.InstructionMap.TryGetValue(instructionId, out var baseActiveStatement)) { return null; } var documentId = await FindChangedDocumentContainingUnmappedActiveStatementAsync(baseActiveStatements, instructionId.Method.Module, baseActiveStatement, solution, cancellationToken).ConfigureAwait(false); if (documentId == null) { // the active statement is contained in an unchanged document, thus it doesn't matter whether it's in an exception region or not return null; } var newDocument = solution.GetRequiredDocument(documentId); var (oldDocument, _) = await LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var analyzer = newDocument.Project.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldDocumentActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); return oldDocumentActiveStatements.GetStatement(baseActiveStatement.Ordinal).ExceptionRegions.IsActiveStatementCovered; } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private async Task<DocumentId?> FindChangedDocumentContainingUnmappedActiveStatementAsync( ActiveStatementsMap activeStatementsMap, Guid moduleId, ActiveStatement baseActiveStatement, Solution newSolution, CancellationToken cancellationToken) { DocumentId? documentId = null; if (TryGetProjectId(moduleId, out var projectId)) { var oldProject = LastCommittedSolution.GetProject(projectId); if (oldProject == null) { // project has been added (should have no active statements under normal circumstances) return null; } var newProject = newSolution.GetProject(projectId); if (newProject == null) { // project has been deleted return null; } documentId = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, cancellationToken).ConfigureAwait(false); } else { // Search for the document in all changed projects in the solution. using var documentFoundCancellationSource = new CancellationTokenSource(); using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(documentFoundCancellationSource.Token, cancellationToken); async Task GetTaskAsync(ProjectId projectId) { var newProject = newSolution.GetRequiredProject(projectId); var id = await GetChangedDocumentContainingUnmappedActiveStatementAsync(activeStatementsMap, LastCommittedSolution, newProject, baseActiveStatement, linkedTokenSource.Token).ConfigureAwait(false); Interlocked.CompareExchange(ref documentId, id, null); if (id != null) { documentFoundCancellationSource.Cancel(); } } var tasks = newSolution.ProjectIds.Select(GetTaskAsync); try { await Task.WhenAll(tasks).ConfigureAwait(false); } catch (OperationCanceledException) when (documentFoundCancellationSource.IsCancellationRequested) { // nop: cancelled because we found the document } } return documentId; } // Enumerate all changed documents in the project whose module contains the active statement. // For each such document enumerate all #line directives to find which maps code to the span that contains the active statement. private static async ValueTask<DocumentId?> GetChangedDocumentContainingUnmappedActiveStatementAsync(ActiveStatementsMap baseActiveStatements, CommittedSolution oldSolution, Project newProject, ActiveStatement activeStatement, CancellationToken cancellationToken) { var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); await foreach (var documentId in EditSession.GetChangedDocumentsAsync(oldSolution, newProject, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); var newDocument = newProject.GetRequiredDocument(documentId); var (oldDocument, _) = await oldSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken).ConfigureAwait(false); if (oldDocument == null) { // Document is out-of-sync, can't reason about its content with respect to the binaries loaded in the debuggee. return null; } var oldActiveStatements = await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); if (oldActiveStatements.Any(s => s.Statement == activeStatement)) { return documentId; } } return null; } private static void ReportTelemetry(DebuggingSessionTelemetry.Data data) { // report telemetry (fire and forget): _ = Task.Run(() => LogTelemetry(data, Logger.Log, LogAggregator.GetNextId)); } private static void LogTelemetry(DebuggingSessionTelemetry.Data debugSessionData, Action<FunctionId, LogMessage> log, Func<int> getNextId) { const string SessionId = nameof(SessionId); const string EditSessionId = nameof(EditSessionId); var debugSessionId = getNextId(); log(FunctionId.Debugging_EncSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map["SessionCount"] = debugSessionData.EditSessionData.Count(session => session.InBreakState); map["EmptySessionCount"] = debugSessionData.EmptyEditSessionCount; map["HotReloadSessionCount"] = debugSessionData.EditSessionData.Count(session => !session.InBreakState); map["EmptyHotReloadSessionCount"] = debugSessionData.EmptyHotReloadEditSessionCount; })); foreach (var editSessionData in debugSessionData.EditSessionData) { var editSessionId = getNextId(); log(FunctionId.Debugging_EncSession_EditSession, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["HadCompilationErrors"] = editSessionData.HadCompilationErrors; map["HadRudeEdits"] = editSessionData.HadRudeEdits; map["HadValidChanges"] = editSessionData.HadValidChanges; map["HadValidInsignificantChanges"] = editSessionData.HadValidInsignificantChanges; map["RudeEditsCount"] = editSessionData.RudeEdits.Length; map["EmitDeltaErrorIdCount"] = editSessionData.EmitErrorIds.Length; map["InBreakState"] = editSessionData.InBreakState; })); foreach (var errorId in editSessionData.EmitErrorIds) { log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["ErrorId"] = errorId; })); } foreach (var (editKind, syntaxKind) in editSessionData.RudeEdits) { log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, KeyValueLogMessage.Create(map => { map[SessionId] = debugSessionId; map[EditSessionId] = editSessionId; map["RudeEditKind"] = editKind; map["RudeEditSyntaxKind"] = syntaxKind; map["RudeEditBlocking"] = editSessionData.HadRudeEdits; })); } } } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly DebuggingSession _instance; public TestAccessor(DebuggingSession instance) => _instance = instance; public void SetNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions) => _instance.NonRemappableRegions = nonRemappableRegions; public ImmutableHashSet<Guid> GetModulesPreparedForUpdate() { lock (_instance._modulesPreparedForUpdateGuard) { return _instance._modulesPreparedForUpdate.ToImmutableHashSet(); } } public EmitBaseline GetProjectEmitBaseline(ProjectId id) { lock (_instance._projectEmitBaselinesGuard) { return _instance._projectEmitBaselines[id]; } } public ImmutableArray<IDisposable> GetBaselineModuleReaders() => _instance.GetBaselineModuleReaders(); public PendingSolutionUpdate? GetPendingSolutionUpdate() => _instance._pendingUpdate; public void SetTelemetryLogger(Action<FunctionId, LogMessage> logger, Func<int> getNextId) => _instance._reportTelemetry = data => LogTelemetry(data, logger, getNextId); } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/DebuggingSessionTelemetry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class DebuggingSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<EditSessionTelemetry.Data> EditSessionData; public readonly int EmptyEditSessionCount; public Data(DebuggingSessionTelemetry telemetry) { EditSessionData = telemetry._editSessionData.ToImmutableArray(); EmptyEditSessionCount = telemetry._emptyEditSessionCount; } } private readonly object _guard = new(); private readonly List<EditSessionTelemetry.Data> _editSessionData; private int _emptyEditSessionCount; public DebuggingSessionTelemetry() => _editSessionData = new List<EditSessionTelemetry.Data>(); public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _editSessionData.Clear(); _emptyEditSessionCount = 0; return data; } } public void LogEditSession(EditSessionTelemetry.Data editSessionTelemetryData) { lock (_guard) { if (editSessionTelemetryData.IsEmpty) { _emptyEditSessionCount++; } else { _editSessionData.Add(editSessionTelemetryData); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class DebuggingSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<EditSessionTelemetry.Data> EditSessionData; public readonly int EmptyEditSessionCount; public readonly int EmptyHotReloadEditSessionCount; public Data(DebuggingSessionTelemetry telemetry) { EditSessionData = telemetry._editSessionData.ToImmutableArray(); EmptyEditSessionCount = telemetry._emptyEditSessionCount; EmptyHotReloadEditSessionCount = telemetry._emptyHotReloadEditSessionCount; } } private readonly object _guard = new(); private readonly List<EditSessionTelemetry.Data> _editSessionData = new(); private int _emptyEditSessionCount; private int _emptyHotReloadEditSessionCount; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _editSessionData.Clear(); _emptyEditSessionCount = 0; _emptyHotReloadEditSessionCount = 0; return data; } } public void LogEditSession(EditSessionTelemetry.Data editSessionTelemetryData) { lock (_guard) { if (editSessionTelemetryData.IsEmpty) { if (editSessionTelemetryData.InBreakState) _emptyEditSessionCount++; else _emptyHotReloadEditSessionCount++; } else { _editSessionData.Add(editSessionTelemetryData); } } } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/EditSession.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions; /// <summary> /// Lazily calculated map of base active statements. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; Telemetry = telemetry; _nonRemappableRegions = debuggingSession.NonRemappableRegions; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id)); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id)); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); var emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, _nonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics); } if (isBlocked) { return SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); } return new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal sealed class EditSession { internal readonly DebuggingSession DebuggingSession; internal readonly EditSessionTelemetry Telemetry; private readonly ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> _nonRemappableRegions; /// <summary> /// Lazily calculated map of base active statements. /// </summary> internal readonly AsyncLazy<ActiveStatementsMap> BaseActiveStatements; /// <summary> /// Cache of document EnC analyses. /// </summary> internal readonly EditAndContinueDocumentAnalysesCache Analyses; internal readonly bool InBreakState; /// <summary> /// A <see cref="DocumentId"/> is added whenever EnC analyzer reports /// rude edits or module diagnostics. At the end of the session we ask the diagnostic analyzer to reanalyze /// the documents to clean up the diagnostics. /// </summary> private readonly HashSet<DocumentId> _documentsWithReportedDiagnostics = new(); private readonly object _documentsWithReportedDiagnosticsGuard = new(); internal EditSession(DebuggingSession debuggingSession, EditSessionTelemetry telemetry, bool inBreakState) { DebuggingSession = debuggingSession; Telemetry = telemetry; _nonRemappableRegions = debuggingSession.NonRemappableRegions; InBreakState = inBreakState; BaseActiveStatements = inBreakState ? new AsyncLazy<ActiveStatementsMap>(cancellationToken => GetBaseActiveStatementsAsync(cancellationToken), cacheResult: true) : new AsyncLazy<ActiveStatementsMap>(ActiveStatementsMap.Empty); Analyses = new EditAndContinueDocumentAnalysesCache(BaseActiveStatements); } /// <summary> /// Errors to be reported when a project is updated but the corresponding module does not support EnC. /// </summary> /// <returns><see langword="default"/> if the module is not loaded.</returns> public async Task<ImmutableArray<Diagnostic>?> GetModuleDiagnosticsAsync(Guid mvid, string projectDisplayName, CancellationToken cancellationToken) { var availability = await DebuggingSession.DebuggerService.GetAvailabilityAsync(mvid, cancellationToken).ConfigureAwait(false); if (availability.Status == ManagedEditAndContinueAvailabilityStatus.ModuleNotLoaded) { return null; } if (availability.Status == ManagedEditAndContinueAvailabilityStatus.Available) { return ImmutableArray<Diagnostic>.Empty; } var descriptor = EditAndContinueDiagnosticDescriptors.GetModuleDiagnosticDescriptor(availability.Status); return ImmutableArray.Create(Diagnostic.Create(descriptor, Location.None, new[] { projectDisplayName, availability.LocalizedMessage })); } private async Task<ActiveStatementsMap> GetBaseActiveStatementsAsync(CancellationToken cancellationToken) { try { // Last committed solution reflects the state of the source that is in sync with the binaries that are loaded in the debuggee. var debugInfos = await DebuggingSession.DebuggerService.GetActiveStatementsAsync(cancellationToken).ConfigureAwait(false); return ActiveStatementsMap.Create(debugInfos, _nonRemappableRegions); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return ActiveStatementsMap.Empty; } } private static async Task PopulateChangedAndAddedDocumentsAsync(CommittedSolution oldSolution, Project newProject, ArrayBuilder<Document> changedOrAddedDocuments, CancellationToken cancellationToken) { changedOrAddedDocuments.Clear(); if (!newProject.SupportsEditAndContinue()) { return; } var oldProject = oldSolution.GetProject(newProject.Id); // When debugging session is started some projects might not have been loaded to the workspace yet. // We capture the base solution. Edits in files that are in projects that haven't been loaded won't be applied // and will result in source mismatch when the user steps into them. // // TODO (https://github.com/dotnet/roslyn/issues/1204): // hook up the debugger reported error, check that the project has not been loaded and report a better error. // Here, we assume these projects are not modified. if (oldProject == null) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not loaded", newProject.Id.DebugName, newProject.Id); return; } if (oldProject.State == newProject.State) { return; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } // Check if the currently observed document content has changed compared to the base document content. // This is an important optimization that aims to avoid IO while stepping in sources that have not changed. // // We may be comparing out-of-date committed document content but we only make a decision based on that content // if it matches the current content. If the current content is equal to baseline content that does not match // the debuggee then the workspace has not observed the change made to the file on disk since baseline was captured // (there had to be one as the content doesn't match). When we are about to apply changes it is ok to ignore this // document because the user does not see the change yet in the buffer (if the doc is open) and won't be confused // if it is not applied yet. The change will be applied later after it's observed by the workspace. var baseSource = await oldProject.GetRequiredDocument(documentId).GetTextAsync(cancellationToken).ConfigureAwait(false); var source = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (baseSource.ContentEquals(source)) { continue; } changedOrAddedDocuments.Add(document); } foreach (var documentId in newProject.State.DocumentStates.GetAddedStateIds(oldProject.State.DocumentStates)) { var document = newProject.GetRequiredDocument(documentId); if (document.State.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(document); } // TODO: support document removal/rename (see https://github.com/dotnet/roslyn/issues/41144, https://github.com/dotnet/roslyn/issues/49013). if (changedOrAddedDocuments.IsEmpty() && !HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. return; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } foreach (var documentId in newSourceGeneratedDocumentStates.GetAddedStateIds(oldSourceGeneratedDocumentStates)) { var newState = newSourceGeneratedDocumentStates.GetRequiredState(documentId); if (newState.Attributes.DesignTimeOnly) { continue; } changedOrAddedDocuments.Add(newProject.GetOrCreateSourceGeneratedDocument(newState)); } } internal static async IAsyncEnumerable<DocumentId> GetChangedDocumentsAsync(CommittedSolution oldSolution, Project newProject, [EnumeratorCancellation] CancellationToken cancellationToken) { var oldProject = oldSolution.GetRequiredProject(newProject.Id); if (!newProject.SupportsEditAndContinue() || oldProject.State == newProject.State) { yield break; } foreach (var documentId in newProject.State.DocumentStates.GetChangedStateIds(oldProject.State.DocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } if (!HasChangesThatMayAffectSourceGenerators(oldProject.State, newProject.State)) { // Based on the above assumption there are no changes in source generated files. yield break; } cancellationToken.ThrowIfCancellationRequested(); var oldSourceGeneratedDocumentStates = await oldProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(oldProject.State, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); var newSourceGeneratedDocumentStates = await newProject.Solution.State.GetSourceGeneratedDocumentStatesAsync(newProject.State, cancellationToken).ConfigureAwait(false); foreach (var documentId in newSourceGeneratedDocumentStates.GetChangedStateIds(oldSourceGeneratedDocumentStates, ignoreUnchangedContent: true)) { yield return documentId; } } /// <summary> /// Given the following assumptions: /// - source generators are deterministic, /// - source documents, metadata references and compilation options have not changed, /// - additional documents have not changed, /// - analyzer config documents have not changed, /// the outputs of source generators will not change. /// /// Currently it's not possible to change compilation options (Project System is readonly during debugging). /// </summary> private static bool HasChangesThatMayAffectSourceGenerators(ProjectState oldProject, ProjectState newProject) => newProject.DocumentStates.HasAnyStateChanges(oldProject.DocumentStates) || newProject.AdditionalDocumentStates.HasAnyStateChanges(oldProject.AdditionalDocumentStates) || newProject.AnalyzerConfigDocumentStates.HasAnyStateChanges(oldProject.AnalyzerConfigDocumentStates); private async Task<(ImmutableArray<DocumentAnalysisResults> results, ImmutableArray<Diagnostic> diagnostics)> AnalyzeDocumentsAsync( ArrayBuilder<Document> changedOrAddedDocuments, ActiveStatementSpanProvider newDocumentActiveStatementSpanProvider, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<Diagnostic>.GetInstance(out var documentDiagnostics); using var _2 = ArrayBuilder<(Document? oldDocument, Document newDocument)>.GetInstance(out var documents); foreach (var newDocument in changedOrAddedDocuments) { var (oldDocument, oldDocumentState) = await DebuggingSession.LastCommittedSolution.GetDocumentAndStateAsync(newDocument.Id, newDocument, cancellationToken, reloadOutOfSyncDocument: true).ConfigureAwait(false); switch (oldDocumentState) { case CommittedSolution.DocumentState.DesignTimeOnly: break; case CommittedSolution.DocumentState.Indeterminate: case CommittedSolution.DocumentState.OutOfSync: var descriptor = EditAndContinueDiagnosticDescriptors.GetDescriptor((oldDocumentState == CommittedSolution.DocumentState.Indeterminate) ? EditAndContinueErrorCode.UnableToReadSourceFileOrPdb : EditAndContinueErrorCode.DocumentIsOutOfSyncWithDebuggee); documentDiagnostics.Add(Diagnostic.Create(descriptor, Location.Create(newDocument.FilePath!, textSpan: default, lineSpan: default), new[] { newDocument.FilePath })); break; case CommittedSolution.DocumentState.MatchesBuildOutput: // Include the document regardless of whether the module it was built into has been loaded or not. // If the module has been built it might get loaded later during the debugging session, // at which point we apply all changes that have been made to the project so far. documents.Add((oldDocument, newDocument)); break; default: throw ExceptionUtilities.UnexpectedValue(oldDocumentState); } } var analyses = await Analyses.GetDocumentAnalysesAsync(DebuggingSession.LastCommittedSolution, documents, newDocumentActiveStatementSpanProvider, DebuggingSession.Capabilities, cancellationToken).ConfigureAwait(false); return (analyses, documentDiagnostics.ToImmutable()); } internal ImmutableArray<DocumentId> GetDocumentsWithReportedDiagnostics() { lock (_documentsWithReportedDiagnosticsGuard) { return ImmutableArray.CreateRange(_documentsWithReportedDiagnostics); } } internal void TrackDocumentWithReportedDiagnostics(DocumentId documentId) { lock (_documentsWithReportedDiagnosticsGuard) { _documentsWithReportedDiagnostics.Add(documentId); } } /// <summary> /// Determines whether projects contain any changes that might need to be applied. /// Checks only projects containing a given <paramref name="sourceFilePath"/> or all projects of the solution if <paramref name="sourceFilePath"/> is null. /// Invoked by the debugger on every step. It is critical for stepping performance that this method returns as fast as possible in absence of changes. /// </summary> public async ValueTask<bool> HasChangesAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken) { try { var baseSolution = DebuggingSession.LastCommittedSolution; if (baseSolution.HasNoChanges(solution)) { return false; } // TODO: source generated files? var projects = (sourceFilePath == null) ? solution.Projects : from documentId in solution.GetDocumentIdsWithFilePath(sourceFilePath) select solution.GetProject(documentId.ProjectId)!; using var _ = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); foreach (var project in projects) { await PopulateChangedAndAddedDocumentsAsync(baseSolution, project, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } // Check MVID before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(project, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // Can't read MVID. This might be an intermittent failure, so don't report it here. // Report the project as containing changes, so that we proceed to EmitSolutionUpdateAsync where we report the error if it still persists. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); return true; } if (mvid == Guid.Empty) { // Project not built. We ignore any changes made in its sources. EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: project not built", project.Id.DebugName, project.Id); continue; } var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: out-of-sync documents present (diagnostic: '{2}')", project.Id.DebugName, project.Id, documentDiagnostics[0]); // Although we do not apply changes in out-of-sync/indeterminate documents we report that changes are present, // so that the debugger triggers emit of updates. There we check if these documents are still in a bad state and report warnings // that any changes in such documents are not applied. return true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary != ProjectAnalysisSummary.NoChanges) { EditAndContinueWorkspaceService.Log.Write("EnC state of '{0}' [0x{1:X8}] queried: {2}", project.Id.DebugName, project.Id, projectSummary); return true; } } return false; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static ProjectAnalysisSummary GetProjectAnalysisSymmary(ImmutableArray<DocumentAnalysisResults> documentAnalyses) { var hasChanges = false; var hasSignificantValidChanges = false; foreach (var analysis in documentAnalyses) { // skip documents that actually were not changed: if (!analysis.HasChanges) { continue; } // rude edit detection wasn't completed due to errors that prevent us from analyzing the document: if (analysis.HasChangesAndSyntaxErrors) { return ProjectAnalysisSummary.CompilationErrors; } // rude edits detected: if (!analysis.RudeEditErrors.IsEmpty) { return ProjectAnalysisSummary.RudeEdits; } hasChanges = true; hasSignificantValidChanges |= analysis.HasSignificantValidChanges; } if (!hasChanges) { // we get here if a document is closed and reopen without any actual change: return ProjectAnalysisSummary.NoChanges; } if (!hasSignificantValidChanges) { return ProjectAnalysisSummary.ValidInsignificantChanges; } return ProjectAnalysisSummary.ValidChanges; } internal static async ValueTask<ProjectChanges> GetProjectChangesAsync( ActiveStatementsMap baseActiveStatements, Compilation oldCompilation, Compilation newCompilation, Project oldProject, Project newProject, ImmutableArray<DocumentAnalysisResults> changedDocumentAnalyses, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var allEdits); using var _2 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var allLineEdits); using var _3 = ArrayBuilder<DocumentActiveStatementChanges>.GetInstance(out var activeStatementsInChangedDocuments); var analyzer = newProject.LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); foreach (var analysis in changedDocumentAnalyses) { if (!analysis.HasSignificantValidChanges) { continue; } // we shouldn't be asking for deltas in presence of errors: Contract.ThrowIfTrue(analysis.HasChangesAndErrors); // Active statements are calculated if document changed and has no syntax errors: Contract.ThrowIfTrue(analysis.ActiveStatements.IsDefault); allEdits.AddRange(analysis.SemanticEdits); allLineEdits.AddRange(analysis.LineEdits); if (analysis.ActiveStatements.Length > 0) { var oldDocument = await oldProject.GetDocumentAsync(analysis.DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var oldActiveStatements = (oldDocument == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : await baseActiveStatements.GetOldActiveStatementsAsync(analyzer, oldDocument, cancellationToken).ConfigureAwait(false); activeStatementsInChangedDocuments.Add(new(oldActiveStatements, analysis.ActiveStatements, analysis.ExceptionRegions)); } } MergePartialEdits(oldCompilation, newCompilation, allEdits, out var mergedEdits, out var addedSymbols, cancellationToken); return new ProjectChanges( mergedEdits, allLineEdits.ToImmutable(), addedSymbols, activeStatementsInChangedDocuments.ToImmutable()); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } internal static void MergePartialEdits( Compilation oldCompilation, Compilation newCompilation, IReadOnlyList<SemanticEditInfo> edits, out ImmutableArray<SemanticEdit> mergedEdits, out ImmutableHashSet<ISymbol> addedSymbols, CancellationToken cancellationToken) { using var _0 = ArrayBuilder<SemanticEdit>.GetInstance(edits.Count, out var mergedEditsBuilder); using var _1 = PooledHashSet<ISymbol>.GetInstance(out var addedSymbolsBuilder); using var _2 = ArrayBuilder<(ISymbol? oldSymbol, ISymbol? newSymbol)>.GetInstance(edits.Count, out var resolvedSymbols); foreach (var edit in edits) { SymbolKeyResolution oldResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Delete) { oldResolution = edit.Symbol.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(oldResolution.Symbol); } else { oldResolution = default; } SymbolKeyResolution newResolution; if (edit.Kind is SemanticEditKind.Update or SemanticEditKind.Insert or SemanticEditKind.Replace) { newResolution = edit.Symbol.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken); Contract.ThrowIfNull(newResolution.Symbol); } else { newResolution = default; } resolvedSymbols.Add((oldResolution.Symbol, newResolution.Symbol)); } for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType == null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (edit.Kind == SemanticEditKind.Insert) { Contract.ThrowIfNull(newSymbol); addedSymbolsBuilder.Add(newSymbol); } mergedEditsBuilder.Add(new SemanticEdit( edit.Kind, oldSymbol: oldSymbol, newSymbol: newSymbol, syntaxMap: edit.SyntaxMap, preserveLocalVariables: edit.SyntaxMap != null)); } } // no partial type merging needed: if (edits.Count == mergedEditsBuilder.Count) { mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); return; } // Calculate merged syntax map for each partial type symbol: var symbolKeyComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); var mergedSyntaxMaps = new Dictionary<SymbolKey, Func<SyntaxNode, SyntaxNode?>?>(symbolKeyComparer); var editsByPartialType = edits .Where(edit => edit.PartialType != null) .GroupBy(edit => edit.PartialType!.Value, symbolKeyComparer); foreach (var partialTypeEdits in editsByPartialType) { // Either all edits have syntax map or none has. Debug.Assert( partialTypeEdits.All(edit => edit.SyntaxMapTree != null && edit.SyntaxMap != null) || partialTypeEdits.All(edit => edit.SyntaxMapTree == null && edit.SyntaxMap == null)); Func<SyntaxNode, SyntaxNode?>? mergedSyntaxMap; if (partialTypeEdits.First().SyntaxMap != null) { var newTrees = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMapTree!); var syntaxMaps = partialTypeEdits.SelectAsArray(edit => edit.SyntaxMap!); mergedSyntaxMap = node => syntaxMaps[newTrees.IndexOf(node.SyntaxTree)](node); } else { mergedSyntaxMap = null; } mergedSyntaxMaps.Add(partialTypeEdits.Key, mergedSyntaxMap); } // Deduplicate edits based on their target symbol and use merged syntax map calculated above for a given partial type. using var _3 = PooledHashSet<ISymbol>.GetInstance(out var visitedSymbols); for (var i = 0; i < edits.Count; i++) { var edit = edits[i]; if (edit.PartialType != null) { var (oldSymbol, newSymbol) = resolvedSymbols[i]; if (visitedSymbols.Add(newSymbol ?? oldSymbol!)) { var syntaxMap = mergedSyntaxMaps[edit.PartialType.Value]; mergedEditsBuilder.Add(new SemanticEdit(edit.Kind, oldSymbol, newSymbol, syntaxMap, preserveLocalVariables: syntaxMap != null)); } } } mergedEdits = mergedEditsBuilder.ToImmutable(); addedSymbols = addedSymbolsBuilder.ToImmutableHashSet(); } public async ValueTask<SolutionUpdate> EmitSolutionUpdateAsync(Solution solution, ActiveStatementSpanProvider solutionActiveStatementSpanProvider, CancellationToken cancellationToken) { try { using var _1 = ArrayBuilder<ManagedModuleUpdate>.GetInstance(out var deltas); using var _2 = ArrayBuilder<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)>.GetInstance(out var nonRemappableRegions); using var _3 = ArrayBuilder<(ProjectId, EmitBaseline)>.GetInstance(out var emitBaselines); using var _4 = ArrayBuilder<(ProjectId, ImmutableArray<Diagnostic>)>.GetInstance(out var diagnostics); using var _5 = ArrayBuilder<Document>.GetInstance(out var changedOrAddedDocuments); using var _6 = ArrayBuilder<(DocumentId, ImmutableArray<RudeEditDiagnostic>)>.GetInstance(out var documentsWithRudeEdits); var oldSolution = DebuggingSession.LastCommittedSolution; var isBlocked = false; foreach (var newProject in solution.Projects) { await PopulateChangedAndAddedDocumentsAsync(oldSolution, newProject, changedOrAddedDocuments, cancellationToken).ConfigureAwait(false); if (changedOrAddedDocuments.IsEmpty()) { continue; } var (mvid, mvidReadError) = await DebuggingSession.GetProjectModuleIdAsync(newProject, cancellationToken).ConfigureAwait(false); if (mvidReadError != null) { // The error hasn't been reported by GetDocumentDiagnosticsAsync since it might have been intermittent. // The MVID is required for emit so we consider the error permanent and report it here. // Bail before analyzing documents as the analysis needs to read the PDB which will likely fail if we can't even read the MVID. diagnostics.Add((newProject.Id, ImmutableArray.Create(mvidReadError))); Telemetry.LogProjectAnalysisSummary(ProjectAnalysisSummary.ValidChanges, ImmutableArray.Create(mvidReadError.Descriptor.Id), InBreakState); isBlocked = true; continue; } if (mvid == Guid.Empty) { EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]: project not built", newProject.Id.DebugName, newProject.Id); continue; } // PopulateChangedAndAddedDocumentsAsync returns no changes if base project does not exist var oldProject = oldSolution.GetProject(newProject.Id); Contract.ThrowIfNull(oldProject); // Ensure that all changed documents are in-sync. Once a document is in-sync it can't get out-of-sync. // Therefore, results of further computations based on base snapshots of changed documents can't be invalidated by // incoming events updating the content of out-of-sync documents. // // If in past we concluded that a document is out-of-sync, attempt to check one more time before we block apply. // The source file content might have been updated since the last time we checked. // // TODO (investigate): https://github.com/dotnet/roslyn/issues/38866 // It is possible that the result of Rude Edit semantic analysis of an unchanged document will change if there // another document is updated. If we encounter a significant case of this we should consider caching such a result per project, // rather then per document. Also, we might be observing an older semantics if the document that is causing the change is out-of-sync -- // e.g. the binary was built with an overload C.M(object), but a generator updated class C to also contain C.M(string), // which change we have not observed yet. Then call-sites of C.M in a changed document observed by the analysis will be seen as C.M(object) // instead of the true C.M(string). var (changedDocumentAnalyses, documentDiagnostics) = await AnalyzeDocumentsAsync(changedOrAddedDocuments, solutionActiveStatementSpanProvider, cancellationToken).ConfigureAwait(false); if (documentDiagnostics.Any()) { // The diagnostic hasn't been reported by GetDocumentDiagnosticsAsync since out-of-sync documents are likely to be synchronized // before the changes are attempted to be applied. If we still have any out-of-sync documents we report warnings and ignore changes in them. // If in future the file is updated so that its content matches the PDB checksum, the document transitions to a matching state, // and we consider any further changes to it for application. diagnostics.Add((newProject.Id, documentDiagnostics)); } // The capability of a module to apply edits may change during edit session if the user attaches debugger to // an additional process that doesn't support EnC (or detaches from such process). Before we apply edits // we need to check with the debugger. var (moduleDiagnostics, isModuleLoaded) = await GetModuleDiagnosticsAsync(mvid, newProject.Name, cancellationToken).ConfigureAwait(false); var isModuleEncBlocked = isModuleLoaded && !moduleDiagnostics.IsEmpty; if (isModuleEncBlocked) { diagnostics.Add((newProject.Id, moduleDiagnostics)); isBlocked = true; } var projectSummary = GetProjectAnalysisSymmary(changedDocumentAnalyses); if (projectSummary == ProjectAnalysisSummary.CompilationErrors) { isBlocked = true; } else if (projectSummary == ProjectAnalysisSummary.RudeEdits) { foreach (var analysis in changedDocumentAnalyses) { if (analysis.RudeEditErrors.Length > 0) { documentsWithRudeEdits.Add((analysis.DocumentId, analysis.RudeEditErrors)); Telemetry.LogRudeEditDiagnostics(analysis.RudeEditErrors); } } isBlocked = true; } if (isModuleEncBlocked || projectSummary != ProjectAnalysisSummary.ValidChanges) { Telemetry.LogProjectAnalysisSummary(projectSummary, moduleDiagnostics.NullToEmpty().SelectAsArray(d => d.Descriptor.Id), InBreakState); continue; } if (!DebuggingSession.TryGetOrCreateEmitBaseline(newProject, out var createBaselineDiagnostics, out var baseline)) { Debug.Assert(!createBaselineDiagnostics.IsEmpty); // Report diagnosics even when the module is never going to be loaded (e.g. in multi-targeting scenario, where only one framework being debugged). // This is consistent with reporting compilation errors - the IDE reports them for all TFMs regardless of what framework the app is running on. diagnostics.Add((newProject.Id, createBaselineDiagnostics)); Telemetry.LogProjectAnalysisSummary(projectSummary, createBaselineDiagnostics, InBreakState); isBlocked = true; continue; } EditAndContinueWorkspaceService.Log.Write("Emitting update of '{0}' [0x{1:X8}]", newProject.Id.DebugName, newProject.Id); var oldCompilation = await oldProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = await newProject.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldCompilation); Contract.ThrowIfNull(newCompilation); var oldActiveStatementsMap = await BaseActiveStatements.GetValueAsync(cancellationToken).ConfigureAwait(false); var projectChanges = await GetProjectChangesAsync(oldActiveStatementsMap, oldCompilation, newCompilation, oldProject, newProject, changedDocumentAnalyses, cancellationToken).ConfigureAwait(false); using var pdbStream = SerializableBytes.CreateWritableStream(); using var metadataStream = SerializableBytes.CreateWritableStream(); using var ilStream = SerializableBytes.CreateWritableStream(); // project must support compilations since it supports EnC Contract.ThrowIfNull(newCompilation); var emitResult = newCompilation.EmitDifference( baseline, projectChanges.SemanticEdits, projectChanges.AddedSymbols.Contains, metadataStream, ilStream, pdbStream, cancellationToken); if (emitResult.Success) { Contract.ThrowIfNull(emitResult.Baseline); var updatedMethodTokens = emitResult.UpdatedMethods.SelectAsArray(h => MetadataTokens.GetToken(h)); var changedTypeTokens = emitResult.ChangedTypes.SelectAsArray(h => MetadataTokens.GetToken(h)); // Determine all active statements whose span changed and exception region span deltas. GetActiveStatementAndExceptionRegionSpans( mvid, oldActiveStatementsMap, updatedMethodTokens, _nonRemappableRegions, projectChanges.ActiveStatementChanges, out var activeStatementsInUpdatedMethods, out var moduleNonRemappableRegions, out var exceptionRegionUpdates); deltas.Add(new ManagedModuleUpdate( mvid, ilStream.ToImmutableArray(), metadataStream.ToImmutableArray(), pdbStream.ToImmutableArray(), projectChanges.LineChanges, updatedMethodTokens, changedTypeTokens, activeStatementsInUpdatedMethods, exceptionRegionUpdates)); nonRemappableRegions.Add((mvid, moduleNonRemappableRegions)); emitBaselines.Add((newProject.Id, emitResult.Baseline)); } else { // error isBlocked = true; } // TODO: https://github.com/dotnet/roslyn/issues/36061 // We should only report diagnostics from emit phase. // Syntax and semantic diagnostics are already reported by the diagnostic analyzer. // Currently we do not have means to distinguish between diagnostics reported from compilation and emit phases. // Querying diagnostics of the entire compilation or just the updated files migth be slow. // In fact, it is desirable to allow emitting deltas for symbols affected by the change while allowing untouched // method bodies to have errors. if (!emitResult.Diagnostics.IsEmpty) { diagnostics.Add((newProject.Id, emitResult.Diagnostics)); } Telemetry.LogProjectAnalysisSummary(projectSummary, emitResult.Diagnostics, InBreakState); } var update = isBlocked ? SolutionUpdate.Blocked(diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()) : new SolutionUpdate( new ManagedModuleUpdates( (deltas.Count > 0) ? ManagedModuleUpdateStatus.Ready : ManagedModuleUpdateStatus.None, deltas.ToImmutable()), nonRemappableRegions.ToImmutable(), emitBaselines.ToImmutable(), diagnostics.ToImmutable(), documentsWithRudeEdits.ToImmutable()); return update; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } // internal for testing internal static void GetActiveStatementAndExceptionRegionSpans( Guid moduleId, ActiveStatementsMap oldActiveStatementMap, ImmutableArray<int> updatedMethodTokens, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> previousNonRemappableRegions, ImmutableArray<DocumentActiveStatementChanges> activeStatementsInChangedDocuments, out ImmutableArray<ManagedActiveStatementUpdate> activeStatementsInUpdatedMethods, out ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)> nonRemappableRegions, out ImmutableArray<ManagedExceptionRegionUpdate> exceptionRegionUpdates) { using var _1 = PooledDictionary<(ManagedModuleMethodId MethodId, SourceFileSpan BaseSpan), SourceFileSpan>.GetInstance(out var changedNonRemappableSpans); var activeStatementsInUpdatedMethodsBuilder = ArrayBuilder<ManagedActiveStatementUpdate>.GetInstance(); var nonRemappableRegionsBuilder = ArrayBuilder<(ManagedModuleMethodId Method, NonRemappableRegion Region)>.GetInstance(); // Process active statements and their exception regions in changed documents of this project/module: foreach (var (oldActiveStatements, newActiveStatements, newExceptionRegions) in activeStatementsInChangedDocuments) { Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Length); Debug.Assert(newActiveStatements.Length == newExceptionRegions.Length); for (var i = 0; i < newActiveStatements.Length; i++) { var (_, oldActiveStatement, oldActiveStatementExceptionRegions) = oldActiveStatements[i]; var newActiveStatement = newActiveStatements[i]; var newActiveStatementExceptionRegions = newExceptionRegions[i]; var instructionId = newActiveStatement.InstructionId; var methodId = instructionId.Method.Method; var isMethodUpdated = updatedMethodTokens.Contains(methodId.Token); if (isMethodUpdated) { activeStatementsInUpdatedMethodsBuilder.Add(new ManagedActiveStatementUpdate(methodId, instructionId.ILOffset, newActiveStatement.Span.ToSourceSpan())); } // Adds a region with specified PDB spans. void AddNonRemappableRegion(SourceFileSpan oldSpan, SourceFileSpan newSpan, bool isExceptionRegion) { // it is a rude edit to change the path of the region span: Debug.Assert(oldSpan.Path == newSpan.Path); if (newActiveStatement.IsMethodUpToDate) { // Start tracking non-remappable regions for active statements in methods that were up-to-date // when break state was entered and now being updated (regardless of whether the active span changed or not). if (isMethodUpdated) { var lineDelta = oldSpan.Span.GetLineDelta(newSpan: newSpan.Span); nonRemappableRegionsBuilder.Add((methodId, new NonRemappableRegion(oldSpan, lineDelta, isExceptionRegion))); } // If the method has been up-to-date and it is not updated now then either the active statement span has not changed, // or the entire method containing it moved. In neither case do we need to start tracking non-remapable region // for the active statement since movement of whole method bodies (if any) is handled only on PDB level without // triggering any remapping on the IL level. } else if (oldSpan.Span != newSpan.Span) { // The method is not up-to-date hence we maintain non-remapable span map for it that needs to be updated. changedNonRemappableSpans[(methodId, oldSpan)] = newSpan; } } AddNonRemappableRegion(oldActiveStatement.FileSpan, newActiveStatement.FileSpan, isExceptionRegion: false); // The spans of the exception regions are known (non-default) for active statements in changed documents // as we ensured earlier that all changed documents are in-sync. for (var j = 0; j < oldActiveStatementExceptionRegions.Spans.Length; j++) { AddNonRemappableRegion(oldActiveStatementExceptionRegions.Spans[j], newActiveStatementExceptionRegions[j], isExceptionRegion: true); } } } activeStatementsInUpdatedMethods = activeStatementsInUpdatedMethodsBuilder.ToImmutableAndFree(); // Gather all active method instances contained in this project/module that are not up-to-date: using var _2 = PooledHashSet<ManagedModuleMethodId>.GetInstance(out var unremappedActiveMethods); foreach (var (instruction, baseActiveStatement) in oldActiveStatementMap.InstructionMap) { if (moduleId == instruction.Method.Module && !baseActiveStatement.IsMethodUpToDate) { unremappedActiveMethods.Add(instruction.Method.Method); } } if (unremappedActiveMethods.Count > 0) { foreach (var (methodInstance, regionsInMethod) in previousNonRemappableRegions) { if (methodInstance.Module != moduleId) { continue; } // Skip non-remappable regions that belong to method instances that are from a different module // or no longer active (all active statements in these method instances have been remapped to newer versions). if (!unremappedActiveMethods.Contains(methodInstance.Method)) { continue; } foreach (var region in regionsInMethod) { // We have calculated changes against a base snapshot (last break state): var baseSpan = region.Span.AddLineDelta(region.LineDelta); NonRemappableRegion newRegion; if (changedNonRemappableSpans.TryGetValue((methodInstance.Method, baseSpan), out var newSpan)) { // all spans must be of the same size: Debug.Assert(newSpan.Span.End.Line - newSpan.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(region.Span.Span.End.Line - region.Span.Span.Start.Line == baseSpan.Span.End.Line - baseSpan.Span.Start.Line); Debug.Assert(newSpan.Path == region.Span.Path); newRegion = region.WithLineDelta(region.Span.Span.GetLineDelta(newSpan: newSpan.Span)); } else { newRegion = region; } nonRemappableRegionsBuilder.Add((methodInstance.Method, newRegion)); } } } nonRemappableRegions = nonRemappableRegionsBuilder.ToImmutableAndFree(); // Note: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1319289 // // The update should include the file name, otherwise it is not possible for the debugger to find // the right IL span of the exception handler in case when multiple handlers in the same method // have the same mapped span but different mapped file name: // // try { active statement } // #line 20 "bar" // catch (IOException) { } // #line 20 "baz" // catch (Exception) { } // // The range span in exception region updates is the new span. Deltas are inverse. // old = new + delta // new = old – delta exceptionRegionUpdates = nonRemappableRegions.SelectAsArray( r => r.Region.IsExceptionRegion, r => new ManagedExceptionRegionUpdate( r.Method, -r.Region.LineDelta, r.Region.Span.AddLineDelta(r.Region.LineDelta).Span.ToSourceSpan())); } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/EditSessionTelemetry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public Data(EditSessionTelemetry telemetry) { RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; } public bool IsEmpty => !(HadCompilationErrors || HadRudeEdits || HadValidChanges || HadValidInsignificantChanges); } private readonly object _guard = new(); private readonly HashSet<(ushort, ushort)> _rudeEdits; private readonly HashSet<string> _emitErrorIds; private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; public EditSessionTelemetry() { _rudeEdits = new HashSet<(ushort, ushort)>(); _emitErrorIds = new HashSet<string>(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; } public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; return data; } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<string> errorsIds) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<Diagnostic> emitDiagnostics) => LogProjectAnalysisSummary(summary, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id)); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { // EncEditSessionInfo is populated on a background thread and then read from the UI thread internal sealed class EditSessionTelemetry { internal readonly struct Data { public readonly ImmutableArray<(ushort EditKind, ushort SyntaxKind)> RudeEdits; public readonly ImmutableArray<string> EmitErrorIds; public readonly bool HadCompilationErrors; public readonly bool HadRudeEdits; public readonly bool HadValidChanges; public readonly bool HadValidInsignificantChanges; public readonly bool InBreakState; public Data(EditSessionTelemetry telemetry) { RudeEdits = telemetry._rudeEdits.AsImmutable(); EmitErrorIds = telemetry._emitErrorIds.AsImmutable(); HadCompilationErrors = telemetry._hadCompilationErrors; HadRudeEdits = telemetry._hadRudeEdits; HadValidChanges = telemetry._hadValidChanges; HadValidInsignificantChanges = telemetry._hadValidInsignificantChanges; InBreakState = telemetry._inBreakState; } public bool IsEmpty => !(HadCompilationErrors || HadRudeEdits || HadValidChanges || HadValidInsignificantChanges); } private readonly object _guard = new(); private readonly HashSet<(ushort, ushort)> _rudeEdits = new(); private readonly HashSet<string> _emitErrorIds = new(); private bool _hadCompilationErrors; private bool _hadRudeEdits; private bool _hadValidChanges; private bool _hadValidInsignificantChanges; private bool _inBreakState; public Data GetDataAndClear() { lock (_guard) { var data = new Data(this); _rudeEdits.Clear(); _emitErrorIds.Clear(); _hadCompilationErrors = false; _hadRudeEdits = false; _hadValidChanges = false; _hadValidInsignificantChanges = false; _inBreakState = false; return data; } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<string> errorsIds, bool inBreakState) { lock (_guard) { _emitErrorIds.AddRange(errorsIds); _inBreakState = inBreakState; switch (summary) { case ProjectAnalysisSummary.NoChanges: break; case ProjectAnalysisSummary.CompilationErrors: _hadCompilationErrors = true; break; case ProjectAnalysisSummary.RudeEdits: _hadRudeEdits = true; break; case ProjectAnalysisSummary.ValidChanges: _hadValidChanges = true; break; case ProjectAnalysisSummary.ValidInsignificantChanges: _hadValidInsignificantChanges = true; break; default: throw ExceptionUtilities.UnexpectedValue(summary); } } } public void LogProjectAnalysisSummary(ProjectAnalysisSummary summary, ImmutableArray<Diagnostic> emitDiagnostics, bool inBreakState) => LogProjectAnalysisSummary(summary, emitDiagnostics.SelectAsArray(d => d.Severity == DiagnosticSeverity.Error, d => d.Id), inBreakState); public void LogRudeEditDiagnostics(ImmutableArray<RudeEditDiagnostic> diagnostics) { lock (_guard) { foreach (var diagnostic in diagnostics) { _rudeEdits.Add(((ushort)diagnostic.Kind, diagnostic.SyntaxKind)); } } } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/SolutionUpdate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostic)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits) => new( new(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Emit; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct SolutionUpdate { public readonly ManagedModuleUpdates ModuleUpdates; public readonly ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> NonRemappableRegions; public readonly ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> EmitBaselines; public readonly ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> Diagnostics; public readonly ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> DocumentsWithRudeEdits; public SolutionUpdate( ManagedModuleUpdates moduleUpdates, ImmutableArray<(Guid ModuleId, ImmutableArray<(ManagedModuleMethodId Method, NonRemappableRegion Region)>)> nonRemappableRegions, ImmutableArray<(ProjectId ProjectId, EmitBaseline Baseline)> emitBaselines, ImmutableArray<(ProjectId ProjectId, ImmutableArray<Diagnostic> Diagnostics)> diagnostics, ImmutableArray<(DocumentId DocumentId, ImmutableArray<RudeEditDiagnostic> Diagnostics)> documentsWithRudeEdits) { ModuleUpdates = moduleUpdates; NonRemappableRegions = nonRemappableRegions; EmitBaselines = emitBaselines; Diagnostics = diagnostics; DocumentsWithRudeEdits = documentsWithRudeEdits; } public static SolutionUpdate Blocked( ImmutableArray<(ProjectId, ImmutableArray<Diagnostic>)> diagnostics, ImmutableArray<(DocumentId, ImmutableArray<RudeEditDiagnostic>)> documentsWithRudeEdits) => new( new(ManagedModuleUpdateStatus.Blocked, ImmutableArray<ManagedModuleUpdate>.Empty), ImmutableArray<(Guid, ImmutableArray<(ManagedModuleMethodId, NonRemappableRegion)>)>.Empty, ImmutableArray<(ProjectId, EmitBaseline)>.Empty, diagnostics, documentsWithRudeEdits); } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/EditAndContinue/TraceLog.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Fixed size rolling tracing log. /// </summary> /// <remarks> /// Recent entries are captured in a memory dump. /// If DEBUG is defined, all entries written to <see cref="DebugWrite(string)"/> or /// <see cref="DebugWrite(string, Arg[])"/> are print to <see cref="Debug"/> output. /// </remarks> internal sealed class TraceLog { internal readonly struct Arg { public readonly object Object; public readonly int Int32; public Arg(object value) { Int32 = 0; Object = value ?? "<null>"; } public Arg(int value) { Int32 = value; Object = null; } public override string ToString() => (Object is null) ? Int32.ToString() : Object.ToString(); public static implicit operator Arg(string value) => new(value); public static implicit operator Arg(int value) => new(value); public static implicit operator Arg(ProjectId value) => new(value.Id.GetHashCode()); public static implicit operator Arg(ProjectAnalysisSummary value) => new(ToString(value)); public static implicit operator Arg(Diagnostic value) => new(value); private static string ToString(ProjectAnalysisSummary summary) => summary switch { ProjectAnalysisSummary.CompilationErrors => nameof(ProjectAnalysisSummary.CompilationErrors), ProjectAnalysisSummary.NoChanges => nameof(ProjectAnalysisSummary.NoChanges), ProjectAnalysisSummary.RudeEdits => nameof(ProjectAnalysisSummary.RudeEdits), ProjectAnalysisSummary.ValidChanges => nameof(ProjectAnalysisSummary.ValidChanges), ProjectAnalysisSummary.ValidInsignificantChanges => nameof(ProjectAnalysisSummary.ValidInsignificantChanges), _ => null, }; } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal readonly struct Entry { public readonly string MessageFormat; public readonly Arg[] ArgsOpt; public Entry(string format, Arg[] argsOpt) { MessageFormat = format; ArgsOpt = argsOpt; } internal string GetDebuggerDisplay() => (MessageFormat == null) ? "" : string.Format(MessageFormat, ArgsOpt?.Select(a => (object)a).ToArray() ?? Array.Empty<object>()); } private readonly Entry[] _log; private readonly string _id; private int _currentLine; public TraceLog(int logSize, string id) { _log = new Entry[logSize]; _id = id; } private void Append(Entry entry) { var index = Interlocked.Increment(ref _currentLine); _log[(index - 1) % _log.Length] = entry; } public void Write(string str) => Write(str, null); public void Write(string format, params Arg[] args) => Append(new Entry(format, args)); [Conditional("DEBUG")] public void DebugWrite(string str) => DebugWrite(str, null); [Conditional("DEBUG")] public void DebugWrite(string format, params Arg[] args) { var entry = new Entry(format, args); Append(entry); Debug.WriteLine(entry.ToString(), _id); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly TraceLog _traceLog; public TestAccessor(TraceLog traceLog) => _traceLog = traceLog; internal Entry[] Entries => _traceLog._log; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; namespace Microsoft.CodeAnalysis.EditAndContinue { /// <summary> /// Fixed size rolling tracing log. /// </summary> /// <remarks> /// Recent entries are captured in a memory dump. /// If DEBUG is defined, all entries written to <see cref="DebugWrite(string)"/> or /// <see cref="DebugWrite(string, Arg[])"/> are print to <see cref="Debug"/> output. /// </remarks> internal sealed class TraceLog { internal readonly struct Arg { public readonly object? Object; public readonly int Int32; public Arg(object? value) { Int32 = -1; Object = value ?? "<null>"; } public Arg(int value, Type? type = null) { Int32 = value; Object = type; } public override string? ToString() => (Object is null) ? Int32.ToString() : (Object is Type { IsEnum: true } type && Int32 >= 0) ? Enum.GetName(type, Int32) : Object.ToString(); public static implicit operator Arg(string? value) => new(value); public static implicit operator Arg(int value) => new(value); public static implicit operator Arg(bool value) => new(value ? "true" : "false"); public static implicit operator Arg(ProjectId value) => new(value.DebugName); public static implicit operator Arg(DocumentId value) => new(value.DebugName); public static implicit operator Arg(Diagnostic value) => new(value); public static implicit operator Arg(ProjectAnalysisSummary value) => new((int)value, typeof(ProjectAnalysisSummary)); public static implicit operator Arg(RudeEditKind value) => new((int)value, typeof(RudeEditKind)); public static implicit operator Arg((int enumValue, Type enumType) value) => new(value.enumValue, value.enumType); } [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal readonly struct Entry { public readonly string MessageFormat; public readonly Arg[]? Args; public Entry(string format, Arg[]? args) { MessageFormat = format; Args = args; } internal string GetDebuggerDisplay() => (MessageFormat == null) ? "" : string.Format(MessageFormat, Args?.Select(a => (object)a).ToArray() ?? Array.Empty<object>()); } private readonly Entry[] _log; private readonly string _id; private int _currentLine; public TraceLog(int logSize, string id) { _log = new Entry[logSize]; _id = id; } private void Append(Entry entry) { var index = Interlocked.Increment(ref _currentLine); _log[(index - 1) % _log.Length] = entry; } public void Write(string str) => Write(str, args: null); public void Write(string format, params Arg[]? args) => Append(new Entry(format, args)); [Conditional("DEBUG")] public void DebugWrite(string str) => DebugWrite(str, args: null); [Conditional("DEBUG")] public void DebugWrite(string format, params Arg[]? args) { var entry = new Entry(format, args); Append(entry); Debug.WriteLine(entry.ToString(), _id); } internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly TraceLog _traceLog; public TestAccessor(TraceLog traceLog) => _traceLog = traceLog; internal Entry[] Entries => _traceLog._log; } } }
1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/Notification/INotificationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Notification { internal interface INotificationService : IWorkspaceService { /// <summary> /// Displays a message box with an OK button to the user. /// </summary> /// <param name="message">The message shown within the message box.</param> /// <param name="title">The title bar to be shown in the message box. May be ignored by some implementations.</param> /// <param name="severity">The severity of the message.</param> void SendNotification( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning); /// <summary> /// Displays a message box with a yes/no question to the user. /// </summary> /// <param name="message">The message shown within the message box.</param> /// <param name="title">The title bar to be shown in the message box. May be ignored by some implementations.</param> /// <param name="severity">The severity of the message.</param> /// <returns>true if yes was clicked, false otherwise.</returns> bool ConfirmMessageBox( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Notification { internal interface INotificationService : IWorkspaceService { /// <summary> /// Displays a message box with an OK button to the user. /// </summary> /// <param name="message">The message shown within the message box.</param> /// <param name="title">The title bar to be shown in the message box. May be ignored by some implementations.</param> /// <param name="severity">The severity of the message.</param> void SendNotification( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning); /// <summary> /// Displays a message box with a yes/no question to the user. /// </summary> /// <param name="message">The message shown within the message box.</param> /// <param name="title">The title bar to be shown in the message box. May be ignored by some implementations.</param> /// <param name="severity">The severity of the message.</param> /// <returns>true if yes was clicked, false otherwise.</returns> bool ConfirmMessageBox( string message, string title = null, NotificationSeverity severity = NotificationSeverity.Warning); } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/UsingDirectiveSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class UsingDirectiveSyntaxExtensions { public static void SortUsingDirectives( this List<UsingDirectiveSyntax> usingDirectives, SyntaxList<UsingDirectiveSyntax> existingDirectives, bool placeSystemNamespaceFirst) { var systemFirstInstance = UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance; var normalInstance = UsingsAndExternAliasesDirectiveComparer.NormalInstance; var specialCaseSystem = placeSystemNamespaceFirst; var comparers = specialCaseSystem ? (systemFirstInstance, normalInstance) : (normalInstance, systemFirstInstance); // First, see if the usings were sorted according to the user's preference. If so, // keep the same sorting after we add the using. However, if the usings weren't sorted // according to their preference, then see if they're sorted in the other way. If so // preserve that sorting as well. That way if the user is working with a file that // was written on a machine with a different default, the usings will stay in a // reasonable order. if (existingDirectives.IsSorted(comparers.Item1)) { usingDirectives.Sort(comparers.Item1); } else if (existingDirectives.IsSorted(comparers.Item2)) { usingDirectives.Sort(comparers.Item2); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class UsingDirectiveSyntaxExtensions { public static void SortUsingDirectives( this List<UsingDirectiveSyntax> usingDirectives, SyntaxList<UsingDirectiveSyntax> existingDirectives, bool placeSystemNamespaceFirst) { var systemFirstInstance = UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance; var normalInstance = UsingsAndExternAliasesDirectiveComparer.NormalInstance; var specialCaseSystem = placeSystemNamespaceFirst; var comparers = specialCaseSystem ? (systemFirstInstance, normalInstance) : (normalInstance, systemFirstInstance); // First, see if the usings were sorted according to the user's preference. If so, // keep the same sorting after we add the using. However, if the usings weren't sorted // according to their preference, then see if they're sorted in the other way. If so // preserve that sorting as well. That way if the user is working with a file that // was written on a machine with a different default, the usings will stay in a // reasonable order. if (existingDirectives.IsSorted(comparers.Item1)) { usingDirectives.Sort(comparers.Item1); } else if (existingDirectives.IsSorted(comparers.Item2)) { usingDirectives.Sort(comparers.Item2); } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DelegateKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DelegateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.UnsafeKeyword }; public DelegateKeywordRecommender() : base(SyntaxKind.DelegateKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || ValidTypeContext(context) || IsAfterAsyncKeywordInExpressionContext(context, cancellationToken) || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); static bool ValidTypeContext(CSharpSyntaxContext context) => (context.IsNonAttributeExpressionContext || context.IsTypeContext) && !context.IsConstantExpressionContext && !context.LeftToken.IsTopLevelOfUsingAliasDirective(); } private static bool IsAfterAsyncKeywordInExpressionContext(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword) && context.SyntaxTree.IsExpressionContext( context.TargetToken.SpanStart, context.TargetToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: context.SemanticModel); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DelegateKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.UnsafeKeyword }; public DelegateKeywordRecommender() : base(SyntaxKind.DelegateKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || ValidTypeContext(context) || IsAfterAsyncKeywordInExpressionContext(context, cancellationToken) || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); static bool ValidTypeContext(CSharpSyntaxContext context) => (context.IsNonAttributeExpressionContext || context.IsTypeContext) && !context.IsConstantExpressionContext && !context.LeftToken.IsTopLevelOfUsingAliasDirective(); } private static bool IsAfterAsyncKeywordInExpressionContext(CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.AsyncKeyword) && context.SyntaxTree.IsExpressionContext( context.TargetToken.SpanStart, context.TargetToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: context.SemanticModel); } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Analyzers/Core/Analyzers/QualifyMemberAccess/AbstractQualifyMemberAccessDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.QualifyMemberAccess { internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer< TLanguageKindEnum, TExpressionSyntax, TSimpleNameSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TExpressionSyntax : SyntaxNode where TSimpleNameSyntax : TExpressionSyntax { protected AbstractQualifyMemberAccessDiagnosticAnalyzer() : base(IDEDiagnosticIds.AddQualificationDiagnosticId, EnforceOnBuildValues.AddQualification, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess), new LocalizableResourceString(nameof(AnalyzersResources.Member_access_should_be_qualified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Add_this_or_Me_qualification), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override bool OpenFileOnly(OptionSet options) { var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, GetLanguageName()).Notification; var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions2.QualifyPropertyAccess, GetLanguageName()).Notification; var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, GetLanguageName()).Notification; var qualifyEventAccessOption = options.GetOption(CodeStyleOptions2.QualifyEventAccess, GetLanguageName()).Notification; return !(qualifyFieldAccessOption == NotificationOption2.Warning || qualifyFieldAccessOption == NotificationOption2.Error || qualifyPropertyAccessOption == NotificationOption2.Warning || qualifyPropertyAccessOption == NotificationOption2.Error || qualifyMethodAccessOption == NotificationOption2.Warning || qualifyMethodAccessOption == NotificationOption2.Error || qualifyEventAccessOption == NotificationOption2.Warning || qualifyEventAccessOption == NotificationOption2.Error); } protected abstract string GetLanguageName(); /// <summary> /// Reports on whether the specified member is suitable for qualification. Some member /// access expressions cannot be qualified; for instance if they begin with <c>base.</c>, /// <c>MyBase.</c>, or <c>MyClass.</c>. /// </summary> /// <returns>True if the member access can be qualified; otherwise, False.</returns> protected abstract bool CanMemberAccessBeQualified(ISymbol containingSymbol, SyntaxNode node); protected abstract bool IsAlreadyQualifiedMemberAccess(TExpressionSyntax node); protected override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.MethodReference, OperationKind.Invocation); protected abstract Location GetLocation(IOperation operation); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeOperation(OperationAnalysisContext context) { if (context.ContainingSymbol.IsStatic) { return; } switch (context.Operation) { case IMemberReferenceOperation memberReferenceOperation: AnalyzeOperation(context, memberReferenceOperation, memberReferenceOperation.Instance); break; case IInvocationOperation invocationOperation: AnalyzeOperation(context, invocationOperation, invocationOperation.Instance); break; default: throw ExceptionUtilities.UnexpectedValue(context.Operation); } } private void AnalyzeOperation(OperationAnalysisContext context, IOperation operation, IOperation instanceOperation) { // this is a static reference so we don't care if it's qualified if (instanceOperation == null) { return; } // if we're not referencing `this.` or `Me.` (e.g., a parameter, local, etc.) if (instanceOperation.Kind != OperationKind.InstanceReference) { return; } // We shouldn't qualify if it is inside a property pattern if (context.Operation.Parent.Kind == OperationKind.PropertySubpattern) { return; } // Initializer lists are IInvocationOperation which if passed to GetApplicableOptionFromSymbolKind // will incorrectly fetch the options for method call. // We still want to handle InstanceReferenceKind.ContainingTypeInstance if ((instanceOperation as IInstanceReferenceOperation)?.ReferenceKind == InstanceReferenceKind.ImplicitReceiver) { return; } // If we can't be qualified (e.g., because we're already qualified with `base.`), we're done. if (!CanMemberAccessBeQualified(context.ContainingSymbol, instanceOperation.Syntax)) { return; } // if we can't find a member then we can't do anything. Also, we shouldn't qualify // accesses to static members. if (IsStaticMemberOrIsLocalFunction(operation)) { return; } if (instanceOperation.Syntax is not TSimpleNameSyntax simpleName) { return; } var applicableOption = QualifyMembersHelpers.GetApplicableOptionFromSymbolKind(operation); var optionValue = context.GetOption(applicableOption, context.Operation.Syntax.Language); var shouldOptionBePresent = optionValue.Value; var severity = optionValue.Notification.Severity; if (!shouldOptionBePresent || severity == ReportDiagnostic.Suppress) { return; } if (!IsAlreadyQualifiedMemberAccess(simpleName)) { context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, GetLocation(operation), severity, additionalLocations: null, properties: null)); } } private static bool IsStaticMemberOrIsLocalFunction(IOperation operation) { return operation switch { IMemberReferenceOperation memberReferenceOperation => IsStaticMemberOrIsLocalFunctionHelper(memberReferenceOperation.Member), IInvocationOperation invocationOperation => IsStaticMemberOrIsLocalFunctionHelper(invocationOperation.TargetMethod), _ => throw ExceptionUtilities.UnexpectedValue(operation), }; static bool IsStaticMemberOrIsLocalFunctionHelper(ISymbol symbol) { return symbol == null || symbol.IsStatic || symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction }; } } } internal static class QualifyMembersHelpers { public static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind) => symbolKind switch { SymbolKind.Field => CodeStyleOptions2.QualifyFieldAccess, SymbolKind.Property => CodeStyleOptions2.QualifyPropertyAccess, SymbolKind.Method => CodeStyleOptions2.QualifyMethodAccess, SymbolKind.Event => CodeStyleOptions2.QualifyEventAccess, _ => throw ExceptionUtilities.UnexpectedValue(symbolKind), }; internal static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(IOperation operation) => operation switch { IMemberReferenceOperation memberReferenceOperation => GetApplicableOptionFromSymbolKind(memberReferenceOperation.Member.Kind), IInvocationOperation invocationOperation => GetApplicableOptionFromSymbolKind(invocationOperation.TargetMethod.Kind), _ => throw ExceptionUtilities.UnexpectedValue(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. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.QualifyMemberAccess { internal abstract class AbstractQualifyMemberAccessDiagnosticAnalyzer< TLanguageKindEnum, TExpressionSyntax, TSimpleNameSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TExpressionSyntax : SyntaxNode where TSimpleNameSyntax : TExpressionSyntax { protected AbstractQualifyMemberAccessDiagnosticAnalyzer() : base(IDEDiagnosticIds.AddQualificationDiagnosticId, EnforceOnBuildValues.AddQualification, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.QualifyFieldAccess, CodeStyleOptions2.QualifyPropertyAccess, CodeStyleOptions2.QualifyMethodAccess, CodeStyleOptions2.QualifyEventAccess), new LocalizableResourceString(nameof(AnalyzersResources.Member_access_should_be_qualified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Add_this_or_Me_qualification), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override bool OpenFileOnly(OptionSet options) { var qualifyFieldAccessOption = options.GetOption(CodeStyleOptions2.QualifyFieldAccess, GetLanguageName()).Notification; var qualifyPropertyAccessOption = options.GetOption(CodeStyleOptions2.QualifyPropertyAccess, GetLanguageName()).Notification; var qualifyMethodAccessOption = options.GetOption(CodeStyleOptions2.QualifyMethodAccess, GetLanguageName()).Notification; var qualifyEventAccessOption = options.GetOption(CodeStyleOptions2.QualifyEventAccess, GetLanguageName()).Notification; return !(qualifyFieldAccessOption == NotificationOption2.Warning || qualifyFieldAccessOption == NotificationOption2.Error || qualifyPropertyAccessOption == NotificationOption2.Warning || qualifyPropertyAccessOption == NotificationOption2.Error || qualifyMethodAccessOption == NotificationOption2.Warning || qualifyMethodAccessOption == NotificationOption2.Error || qualifyEventAccessOption == NotificationOption2.Warning || qualifyEventAccessOption == NotificationOption2.Error); } protected abstract string GetLanguageName(); /// <summary> /// Reports on whether the specified member is suitable for qualification. Some member /// access expressions cannot be qualified; for instance if they begin with <c>base.</c>, /// <c>MyBase.</c>, or <c>MyClass.</c>. /// </summary> /// <returns>True if the member access can be qualified; otherwise, False.</returns> protected abstract bool CanMemberAccessBeQualified(ISymbol containingSymbol, SyntaxNode node); protected abstract bool IsAlreadyQualifiedMemberAccess(TExpressionSyntax node); protected override void InitializeWorker(AnalysisContext context) => context.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference, OperationKind.PropertyReference, OperationKind.MethodReference, OperationKind.Invocation); protected abstract Location GetLocation(IOperation operation); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeOperation(OperationAnalysisContext context) { if (context.ContainingSymbol.IsStatic) { return; } switch (context.Operation) { case IMemberReferenceOperation memberReferenceOperation: AnalyzeOperation(context, memberReferenceOperation, memberReferenceOperation.Instance); break; case IInvocationOperation invocationOperation: AnalyzeOperation(context, invocationOperation, invocationOperation.Instance); break; default: throw ExceptionUtilities.UnexpectedValue(context.Operation); } } private void AnalyzeOperation(OperationAnalysisContext context, IOperation operation, IOperation instanceOperation) { // this is a static reference so we don't care if it's qualified if (instanceOperation == null) { return; } // if we're not referencing `this.` or `Me.` (e.g., a parameter, local, etc.) if (instanceOperation.Kind != OperationKind.InstanceReference) { return; } // We shouldn't qualify if it is inside a property pattern if (context.Operation.Parent.Kind == OperationKind.PropertySubpattern) { return; } // Initializer lists are IInvocationOperation which if passed to GetApplicableOptionFromSymbolKind // will incorrectly fetch the options for method call. // We still want to handle InstanceReferenceKind.ContainingTypeInstance if ((instanceOperation as IInstanceReferenceOperation)?.ReferenceKind == InstanceReferenceKind.ImplicitReceiver) { return; } // If we can't be qualified (e.g., because we're already qualified with `base.`), we're done. if (!CanMemberAccessBeQualified(context.ContainingSymbol, instanceOperation.Syntax)) { return; } // if we can't find a member then we can't do anything. Also, we shouldn't qualify // accesses to static members. if (IsStaticMemberOrIsLocalFunction(operation)) { return; } if (instanceOperation.Syntax is not TSimpleNameSyntax simpleName) { return; } var applicableOption = QualifyMembersHelpers.GetApplicableOptionFromSymbolKind(operation); var optionValue = context.GetOption(applicableOption, context.Operation.Syntax.Language); var shouldOptionBePresent = optionValue.Value; var severity = optionValue.Notification.Severity; if (!shouldOptionBePresent || severity == ReportDiagnostic.Suppress) { return; } if (!IsAlreadyQualifiedMemberAccess(simpleName)) { context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, GetLocation(operation), severity, additionalLocations: null, properties: null)); } } private static bool IsStaticMemberOrIsLocalFunction(IOperation operation) { return operation switch { IMemberReferenceOperation memberReferenceOperation => IsStaticMemberOrIsLocalFunctionHelper(memberReferenceOperation.Member), IInvocationOperation invocationOperation => IsStaticMemberOrIsLocalFunctionHelper(invocationOperation.TargetMethod), _ => throw ExceptionUtilities.UnexpectedValue(operation), }; static bool IsStaticMemberOrIsLocalFunctionHelper(ISymbol symbol) { return symbol == null || symbol.IsStatic || symbol is IMethodSymbol { MethodKind: MethodKind.LocalFunction }; } } } internal static class QualifyMembersHelpers { public static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(SymbolKind symbolKind) => symbolKind switch { SymbolKind.Field => CodeStyleOptions2.QualifyFieldAccess, SymbolKind.Property => CodeStyleOptions2.QualifyPropertyAccess, SymbolKind.Method => CodeStyleOptions2.QualifyMethodAccess, SymbolKind.Event => CodeStyleOptions2.QualifyEventAccess, _ => throw ExceptionUtilities.UnexpectedValue(symbolKind), }; internal static PerLanguageOption2<CodeStyleOption2<bool>> GetApplicableOptionFromSymbolKind(IOperation operation) => operation switch { IMemberReferenceOperation memberReferenceOperation => GetApplicableOptionFromSymbolKind(memberReferenceOperation.Member.Kind), IInvocationOperation invocationOperation => GetApplicableOptionFromSymbolKind(invocationOperation.TargetMethod.Kind), _ => throw ExceptionUtilities.UnexpectedValue(operation), }; } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.StateManager.HostStates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { private partial class StateManager { public IEnumerable<StateSet> GetAllHostStateSets() => _hostAnalyzerStateMap.Values.SelectMany(v => v.OrderedStateSets); private HostAnalyzerStateSets GetOrCreateHostStateSets(Project project, ProjectAnalyzerStateSets projectStateSets) { var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, project.Language, CreateLanguageSpecificAnalyzerMap, project.Solution.State.Analyzers); return hostStateSets.WithExcludedAnalyzers(projectStateSets.SkippedAnalyzersInfo.SkippedAnalyzers); static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(string language, HostDiagnosticAnalyzers hostAnalyzers) { var analyzersPerReference = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language); var analyzerMap = CreateStateSetMap(language, analyzersPerReference.Values, includeFileContentLoadAnalyzer: true); VerifyUniqueStateNames(analyzerMap.Values); return new HostAnalyzerStateSets(analyzerMap); } } private sealed class HostAnalyzerStateSets { private const int FileContentLoadAnalyzerPriority = -3; private const int BuiltInCompilerPriority = -2; private const int RegularDiagnosticAnalyzerPriority = -1; // ordered by priority public readonly ImmutableArray<StateSet> OrderedStateSets; public readonly ImmutableDictionary<DiagnosticAnalyzer, StateSet> StateSetMap; private HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> stateSetMap, ImmutableArray<StateSet> orderedStateSets) { StateSetMap = stateSetMap; OrderedStateSets = orderedStateSets; } public HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> analyzerMap) { StateSetMap = analyzerMap; // order statesets // order will be in this order // BuiltIn Compiler Analyzer (C#/VB) < Regular DiagnosticAnalyzers < Document/ProjectDiagnosticAnalyzers OrderedStateSets = StateSetMap.Values.OrderBy(PriorityComparison).ToImmutableArray(); } public HostAnalyzerStateSets WithExcludedAnalyzers(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers) { if (excludedAnalyzers.IsEmpty) { return this; } var stateSetMap = StateSetMap.Where(kvp => !excludedAnalyzers.Contains(kvp.Key)).ToImmutableDictionary(); var orderedStateSets = OrderedStateSets.WhereAsArray(stateSet => !excludedAnalyzers.Contains(stateSet.Analyzer)); return new HostAnalyzerStateSets(stateSetMap, orderedStateSets); } private int PriorityComparison(StateSet state1, StateSet state2) => GetPriority(state1) - GetPriority(state2); private static int GetPriority(StateSet state) { // compiler gets highest priority if (state.Analyzer.IsCompilerAnalyzer()) { return BuiltInCompilerPriority; } return state.Analyzer switch { FileContentLoadAnalyzer _ => FileContentLoadAnalyzerPriority, DocumentDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority), ProjectDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority), _ => RegularDiagnosticAnalyzerPriority, }; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { private partial class StateManager { public IEnumerable<StateSet> GetAllHostStateSets() => _hostAnalyzerStateMap.Values.SelectMany(v => v.OrderedStateSets); private HostAnalyzerStateSets GetOrCreateHostStateSets(Project project, ProjectAnalyzerStateSets projectStateSets) { var hostStateSets = ImmutableInterlocked.GetOrAdd(ref _hostAnalyzerStateMap, project.Language, CreateLanguageSpecificAnalyzerMap, project.Solution.State.Analyzers); return hostStateSets.WithExcludedAnalyzers(projectStateSets.SkippedAnalyzersInfo.SkippedAnalyzers); static HostAnalyzerStateSets CreateLanguageSpecificAnalyzerMap(string language, HostDiagnosticAnalyzers hostAnalyzers) { var analyzersPerReference = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(language); var analyzerMap = CreateStateSetMap(language, analyzersPerReference.Values, includeFileContentLoadAnalyzer: true); VerifyUniqueStateNames(analyzerMap.Values); return new HostAnalyzerStateSets(analyzerMap); } } private sealed class HostAnalyzerStateSets { private const int FileContentLoadAnalyzerPriority = -3; private const int BuiltInCompilerPriority = -2; private const int RegularDiagnosticAnalyzerPriority = -1; // ordered by priority public readonly ImmutableArray<StateSet> OrderedStateSets; public readonly ImmutableDictionary<DiagnosticAnalyzer, StateSet> StateSetMap; private HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> stateSetMap, ImmutableArray<StateSet> orderedStateSets) { StateSetMap = stateSetMap; OrderedStateSets = orderedStateSets; } public HostAnalyzerStateSets(ImmutableDictionary<DiagnosticAnalyzer, StateSet> analyzerMap) { StateSetMap = analyzerMap; // order statesets // order will be in this order // BuiltIn Compiler Analyzer (C#/VB) < Regular DiagnosticAnalyzers < Document/ProjectDiagnosticAnalyzers OrderedStateSets = StateSetMap.Values.OrderBy(PriorityComparison).ToImmutableArray(); } public HostAnalyzerStateSets WithExcludedAnalyzers(ImmutableHashSet<DiagnosticAnalyzer> excludedAnalyzers) { if (excludedAnalyzers.IsEmpty) { return this; } var stateSetMap = StateSetMap.Where(kvp => !excludedAnalyzers.Contains(kvp.Key)).ToImmutableDictionary(); var orderedStateSets = OrderedStateSets.WhereAsArray(stateSet => !excludedAnalyzers.Contains(stateSet.Analyzer)); return new HostAnalyzerStateSets(stateSetMap, orderedStateSets); } private int PriorityComparison(StateSet state1, StateSet state2) => GetPriority(state1) - GetPriority(state2); private static int GetPriority(StateSet state) { // compiler gets highest priority if (state.Analyzer.IsCompilerAnalyzer()) { return BuiltInCompilerPriority; } return state.Analyzer switch { FileContentLoadAnalyzer _ => FileContentLoadAnalyzerPriority, DocumentDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority), ProjectDiagnosticAnalyzer analyzer => Math.Max(0, analyzer.Priority), _ => RegularDiagnosticAnalyzerPriority, }; } } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/Core/Portable/Workspace/Solution/Project.EquivalenceResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public partial class Project { private class EquivalenceResult { public readonly bool PubliclyEquivalent; public readonly bool PrivatelyEquivalent; public EquivalenceResult(bool publiclyEquivalent, bool privatelyEquivalent) { this.PubliclyEquivalent = publiclyEquivalent; this.PrivatelyEquivalent = privatelyEquivalent; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis { public partial class Project { private class EquivalenceResult { public readonly bool PubliclyEquivalent; public readonly bool PrivatelyEquivalent; public EquivalenceResult(bool publiclyEquivalent, bool privatelyEquivalent) { this.PubliclyEquivalent = publiclyEquivalent; this.PrivatelyEquivalent = privatelyEquivalent; } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Compilers/CSharp/Portable/Lowering/Instrumentation/Instrumenter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A base class for components that instrument various portions of executable code. /// It provides a set of APIs that are called by <see cref="LocalRewriter"/> to instrument /// specific portions of the code. These APIs have at least two parameters: /// - original bound node produced by the <see cref="Binder"/> for the relevant portion of the code; /// - rewritten bound node created by the <see cref="LocalRewriter"/> for the original node. /// The APIs are expected to return new state of the rewritten node, after they apply appropriate /// modifications, if any. /// /// The base class provides default implementation for all APIs, which simply returns the rewritten node. /// </summary> internal class Instrumenter { /// <summary> /// The singleton NoOp instrumenter, can be used to terminate the chain of <see cref="CompoundInstrumenter"/>s. /// </summary> public static readonly Instrumenter NoOp = new Instrumenter(); public Instrumenter() { } private static BoundStatement InstrumentStatement(BoundStatement original, BoundStatement rewritten) { Debug.Assert(!original.WasCompilerGenerated); return rewritten; } public virtual BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) { Debug.Assert(!original.WasCompilerGenerated || original.Syntax.Kind() == SyntaxKind.Block); return rewritten; } public virtual BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } /// <summary> /// Return a node that is associated with open brace of the block. Ok to return null. /// </summary> public virtual BoundStatement? CreateBlockPrologue(BoundBlock original, out Symbols.LocalSymbol? synthesizedLocal) { synthesizedLocal = null; return null; } /// <summary> /// Return a node that is associated with close brace of the block. Ok to return null. /// </summary> public virtual BoundStatement? CreateBlockEpilogue(BoundBlock original) { return null; } public virtual BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) { Debug.Assert(LocalRewriter.IsFieldOrPropertyInitializer(original)); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.DoStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.WhileStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentDoStatementConditionalGotoStart(BoundDoStatement original, BoundStatement ifConditionGotoStart) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.DoStatement); return ifConditionGotoStart; } public virtual BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.WhileStatement); return ifConditionGotoStart; } [return: NotNullIfNotNull("collectionVarDecl")] public virtual BoundStatement? InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, BoundStatement? collectionVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return collectionVarDecl; } public virtual BoundStatement InstrumentForEachStatement(BoundForEachStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForEachStatement); return iterationVarDecl; } public virtual BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForEachVariableStatement); return iterationVarDecl; } public virtual BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return branchBack; } public virtual BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForStatement); return branchBack; } public virtual BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.IfStatement); return InstrumentStatement(original, rewritten); } public virtual BoundExpression InstrumentIfStatementCondition(BoundIfStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.IfStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentLabelStatement(BoundLabeledStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.LabeledStatement); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.VariableDeclarator || (original.Syntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)original.Syntax).Declaration.Variables.Count == 1)); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.LockStatement); return lockTargetCapture; } public virtual BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) { return rewritten; } public virtual BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.SwitchStatement); return InstrumentStatement(original, rewritten); } /// <summary> /// Instrument a switch case when clause, which is translated to a conditional branch to the body of the case block. /// </summary> /// <param name="original">the bound expression of the when clause</param> /// <param name="ifConditionGotoBody">the lowered conditional branch into the case block</param> public virtual BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.FirstAncestorOrSelf<WhenClauseSyntax>() != null); return ifConditionGotoBody; } public virtual BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.UsingStatement); return usingTargetCapture; } public virtual BoundExpression InstrumentCatchClauseFilter(BoundCatchBlock original, BoundExpression rewrittenFilter, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.CatchClause); Debug.Assert(((CatchClauseSyntax)original.Syntax).Filter != null); Debug.Assert(factory != null); return rewrittenFilter; } public virtual BoundExpression InstrumentSwitchStatementExpression(BoundStatement original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) { Debug.Assert(original.Kind == BoundKind.SwitchStatement); Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.SwitchStatement); Debug.Assert(factory != null); return rewrittenExpression; } /// <summary> /// Instrument the expression of a switch arm of a switch expression. /// </summary> public virtual BoundExpression InstrumentSwitchExpressionArmExpression(BoundExpression original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) { Debug.Assert(factory != null); return rewrittenExpression; } public virtual BoundStatement InstrumentSwitchBindCasePatternVariables(BoundStatement bindings) { return bindings; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A base class for components that instrument various portions of executable code. /// It provides a set of APIs that are called by <see cref="LocalRewriter"/> to instrument /// specific portions of the code. These APIs have at least two parameters: /// - original bound node produced by the <see cref="Binder"/> for the relevant portion of the code; /// - rewritten bound node created by the <see cref="LocalRewriter"/> for the original node. /// The APIs are expected to return new state of the rewritten node, after they apply appropriate /// modifications, if any. /// /// The base class provides default implementation for all APIs, which simply returns the rewritten node. /// </summary> internal class Instrumenter { /// <summary> /// The singleton NoOp instrumenter, can be used to terminate the chain of <see cref="CompoundInstrumenter"/>s. /// </summary> public static readonly Instrumenter NoOp = new Instrumenter(); public Instrumenter() { } private static BoundStatement InstrumentStatement(BoundStatement original, BoundStatement rewritten) { Debug.Assert(!original.WasCompilerGenerated); return rewritten; } public virtual BoundStatement InstrumentNoOpStatement(BoundNoOpStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentYieldBreakStatement(BoundYieldBreakStatement original, BoundStatement rewritten) { Debug.Assert(!original.WasCompilerGenerated || original.Syntax.Kind() == SyntaxKind.Block); return rewritten; } public virtual BoundStatement InstrumentYieldReturnStatement(BoundYieldReturnStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } /// <summary> /// Return a node that is associated with open brace of the block. Ok to return null. /// </summary> public virtual BoundStatement? CreateBlockPrologue(BoundBlock original, out Symbols.LocalSymbol? synthesizedLocal) { synthesizedLocal = null; return null; } /// <summary> /// Return a node that is associated with close brace of the block. Ok to return null. /// </summary> public virtual BoundStatement? CreateBlockEpilogue(BoundBlock original) { return null; } public virtual BoundStatement InstrumentThrowStatement(BoundThrowStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentContinueStatement(BoundContinueStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentGotoStatement(BoundGotoStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentExpressionStatement(BoundExpressionStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentFieldOrPropertyInitializer(BoundStatement original, BoundStatement rewritten) { Debug.Assert(LocalRewriter.IsFieldOrPropertyInitializer(original)); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentBreakStatement(BoundBreakStatement original, BoundStatement rewritten) { return InstrumentStatement(original, rewritten); } public virtual BoundExpression InstrumentDoStatementCondition(BoundDoStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.DoStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundExpression InstrumentWhileStatementCondition(BoundWhileStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.WhileStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentDoStatementConditionalGotoStart(BoundDoStatement original, BoundStatement ifConditionGotoStart) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.DoStatement); return ifConditionGotoStart; } public virtual BoundStatement InstrumentWhileStatementConditionalGotoStartOrBreak(BoundWhileStatement original, BoundStatement ifConditionGotoStart) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.WhileStatement); return ifConditionGotoStart; } [return: NotNullIfNotNull("collectionVarDecl")] public virtual BoundStatement? InstrumentForEachStatementCollectionVarDeclaration(BoundForEachStatement original, BoundStatement? collectionVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return collectionVarDecl; } public virtual BoundStatement InstrumentForEachStatement(BoundForEachStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentForEachStatementIterationVarDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForEachStatement); return iterationVarDecl; } public virtual BoundStatement InstrumentForEachStatementDeconstructionVariablesDeclaration(BoundForEachStatement original, BoundStatement iterationVarDecl) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForEachVariableStatement); return iterationVarDecl; } public virtual BoundStatement InstrumentForEachStatementConditionalGotoStart(BoundForEachStatement original, BoundStatement branchBack) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax is CommonForEachStatementSyntax); return branchBack; } public virtual BoundStatement InstrumentForStatementConditionalGotoStartOrBreak(BoundForStatement original, BoundStatement branchBack) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForStatement); return branchBack; } public virtual BoundExpression InstrumentForStatementCondition(BoundForStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.ForStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentIfStatement(BoundIfStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.IfStatement); return InstrumentStatement(original, rewritten); } public virtual BoundExpression InstrumentIfStatementCondition(BoundIfStatement original, BoundExpression rewrittenCondition, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.IfStatement); Debug.Assert(factory != null); return rewrittenCondition; } public virtual BoundStatement InstrumentLabelStatement(BoundLabeledStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.LabeledStatement); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentLocalInitialization(BoundLocalDeclaration original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.VariableDeclarator || (original.Syntax.Kind() == SyntaxKind.LocalDeclarationStatement && ((LocalDeclarationStatementSyntax)original.Syntax).Declaration.Variables.Count == 1)); return InstrumentStatement(original, rewritten); } public virtual BoundStatement InstrumentLockTargetCapture(BoundLockStatement original, BoundStatement lockTargetCapture) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.LockStatement); return lockTargetCapture; } public virtual BoundStatement InstrumentReturnStatement(BoundReturnStatement original, BoundStatement rewritten) { return rewritten; } public virtual BoundStatement InstrumentSwitchStatement(BoundSwitchStatement original, BoundStatement rewritten) { Debug.Assert(original.Syntax.Kind() == SyntaxKind.SwitchStatement); return InstrumentStatement(original, rewritten); } /// <summary> /// Instrument a switch case when clause, which is translated to a conditional branch to the body of the case block. /// </summary> /// <param name="original">the bound expression of the when clause</param> /// <param name="ifConditionGotoBody">the lowered conditional branch into the case block</param> public virtual BoundStatement InstrumentSwitchWhenClauseConditionalGotoBody(BoundExpression original, BoundStatement ifConditionGotoBody) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.FirstAncestorOrSelf<WhenClauseSyntax>() != null); return ifConditionGotoBody; } public virtual BoundStatement InstrumentUsingTargetCapture(BoundUsingStatement original, BoundStatement usingTargetCapture) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.UsingStatement); return usingTargetCapture; } public virtual BoundExpression InstrumentCatchClauseFilter(BoundCatchBlock original, BoundExpression rewrittenFilter, SyntheticBoundNodeFactory factory) { Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.CatchClause); Debug.Assert(((CatchClauseSyntax)original.Syntax).Filter != null); Debug.Assert(factory != null); return rewrittenFilter; } public virtual BoundExpression InstrumentSwitchStatementExpression(BoundStatement original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) { Debug.Assert(original.Kind == BoundKind.SwitchStatement); Debug.Assert(!original.WasCompilerGenerated); Debug.Assert(original.Syntax.Kind() == SyntaxKind.SwitchStatement); Debug.Assert(factory != null); return rewrittenExpression; } /// <summary> /// Instrument the expression of a switch arm of a switch expression. /// </summary> public virtual BoundExpression InstrumentSwitchExpressionArmExpression(BoundExpression original, BoundExpression rewrittenExpression, SyntheticBoundNodeFactory factory) { Debug.Assert(factory != null); return rewrittenExpression; } public virtual BoundStatement InstrumentSwitchBindCasePatternVariables(BoundStatement bindings) { return bindings; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Scripting/Core/ScriptMetadataResolver.cs
// Licensed to the .NET Foundation under one or more 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 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; public sealed class ScriptMetadataResolver : MetadataReferenceResolver, IEquatable<ScriptMetadataResolver> { public static ScriptMetadataResolver Default { get; } = new ScriptMetadataResolver( RuntimeMetadataReferenceResolver.CreateCurrentPlatformResolver(ImmutableArray<string>.Empty, baseDirectory: null)); private readonly RuntimeMetadataReferenceResolver _resolver; public ImmutableArray<string> SearchPaths => _resolver.PathResolver.SearchPaths; public string BaseDirectory => _resolver.PathResolver.BaseDirectory; internal ScriptMetadataResolver(RuntimeMetadataReferenceResolver resolver) { _resolver = resolver; } public ScriptMetadataResolver WithSearchPaths(params string[] searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(IEnumerable<string> searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(ImmutableArray<string> searchPaths) { if (SearchPaths == searchPaths) { return this; } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithSearchPaths(ToImmutableArrayChecked(searchPaths, nameof(searchPaths))))); } public ScriptMetadataResolver WithBaseDirectory(string? baseDirectory) { if (BaseDirectory == baseDirectory) { return this; } if (baseDirectory != null) { CompilerPathUtilities.RequireAbsolutePath(baseDirectory, nameof(baseDirectory)); } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithBaseDirectory(baseDirectory))); } public override bool ResolveMissingAssemblies => _resolver.ResolveMissingAssemblies; public override PortableExecutableReference? ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) => _resolver.ResolveMissingAssembly(definition, referenceIdentity); public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) => _resolver.ResolveReference(reference, baseFilePath, properties); public bool Equals(ScriptMetadataResolver? other) => _resolver.Equals(other); public override bool Equals(object? other) => Equals(other as ScriptMetadataResolver); public override int GetHashCode() => _resolver.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma warning disable 436 // The type 'RelativePathResolver' conflicts with imported type using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Scripting.Hosting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting { using static ParameterValidationHelpers; public sealed class ScriptMetadataResolver : MetadataReferenceResolver, IEquatable<ScriptMetadataResolver> { public static ScriptMetadataResolver Default { get; } = new ScriptMetadataResolver( RuntimeMetadataReferenceResolver.CreateCurrentPlatformResolver(ImmutableArray<string>.Empty, baseDirectory: null)); private readonly RuntimeMetadataReferenceResolver _resolver; public ImmutableArray<string> SearchPaths => _resolver.PathResolver.SearchPaths; public string BaseDirectory => _resolver.PathResolver.BaseDirectory; internal ScriptMetadataResolver(RuntimeMetadataReferenceResolver resolver) { _resolver = resolver; } public ScriptMetadataResolver WithSearchPaths(params string[] searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(IEnumerable<string> searchPaths) => WithSearchPaths(searchPaths.AsImmutableOrEmpty()); public ScriptMetadataResolver WithSearchPaths(ImmutableArray<string> searchPaths) { if (SearchPaths == searchPaths) { return this; } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithSearchPaths(ToImmutableArrayChecked(searchPaths, nameof(searchPaths))))); } public ScriptMetadataResolver WithBaseDirectory(string? baseDirectory) { if (BaseDirectory == baseDirectory) { return this; } if (baseDirectory != null) { CompilerPathUtilities.RequireAbsolutePath(baseDirectory, nameof(baseDirectory)); } return new ScriptMetadataResolver(_resolver.WithRelativePathResolver( _resolver.PathResolver.WithBaseDirectory(baseDirectory))); } public override bool ResolveMissingAssemblies => _resolver.ResolveMissingAssemblies; public override PortableExecutableReference? ResolveMissingAssembly(MetadataReference definition, AssemblyIdentity referenceIdentity) => _resolver.ResolveMissingAssembly(definition, referenceIdentity); public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string? baseFilePath, MetadataReferenceProperties properties) => _resolver.ResolveReference(reference, baseFilePath, properties); public bool Equals(ScriptMetadataResolver? other) => _resolver.Equals(other); public override bool Equals(object? other) => Equals(other as ScriptMetadataResolver); public override int GetHashCode() => _resolver.GetHashCode(); } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/CSharp/Portable/CodeRefactorings/InlineTemporary/InlineTemporaryCodeRefactoringProvider.InitializerRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary { internal partial class InlineTemporaryCodeRefactoringProvider { /// <summary> /// This class handles rewriting initializer expressions that refer to the variable /// being initialized into a simpler form. For example, in "int x = x = 1", we want to /// get just "1" back as the initializer. /// </summary> private class InitializerRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private readonly ILocalSymbol _localSymbol; private InitializerRewriter(ILocalSymbol localSymbol, SemanticModel semanticModel) { _semanticModel = semanticModel; _localSymbol = localSymbol; } private bool IsReference(SimpleNameSyntax name) { if (name.Identifier.ValueText != _localSymbol.Name) { return false; } var symbol = _semanticModel.GetSymbolInfo(name).Symbol; return symbol != null && symbol.Equals(_localSymbol); } public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node) { // Note - leave this as SyntaxNode for now, we might have already re-written it var newNode = base.VisitAssignmentExpression(node); if (newNode.Kind() == SyntaxKind.SimpleAssignmentExpression) { // It's okay to just look at the text, since we're explicitly looking for an // identifier standing alone, and we know we're in a local's initializer. // The text can only bind to the initializer. var assignment = (AssignmentExpressionSyntax)newNode; var name = assignment.Left.Kind() == SyntaxKind.IdentifierName ? (IdentifierNameSyntax)assignment.Left : null; if (name != null && IsReference(name)) { return assignment.Right; } } return newNode; } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if (IsReference(node)) { if (node.Parent is AssignmentExpressionSyntax assignmentExpression) { if (assignmentExpression.IsCompoundAssignExpression() && assignmentExpression.Left == node) { return node.Update(node.Identifier.WithAdditionalAnnotations(CreateConflictAnnotation())); } } } return base.VisitIdentifierName(node); } public override SyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { var newNode = base.VisitParenthesizedExpression(node); if (node != newNode && newNode.Kind() == SyntaxKind.ParenthesizedExpression) { return newNode.WithAdditionalAnnotations(Simplifier.Annotation); } return newNode; } public static ExpressionSyntax Visit(ExpressionSyntax initializer, ILocalSymbol local, SemanticModel semanticModel) { var simplifier = new InitializerRewriter(local, semanticModel); return (ExpressionSyntax)simplifier.Visit(initializer); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary { internal partial class InlineTemporaryCodeRefactoringProvider { /// <summary> /// This class handles rewriting initializer expressions that refer to the variable /// being initialized into a simpler form. For example, in "int x = x = 1", we want to /// get just "1" back as the initializer. /// </summary> private class InitializerRewriter : CSharpSyntaxRewriter { private readonly SemanticModel _semanticModel; private readonly ILocalSymbol _localSymbol; private InitializerRewriter(ILocalSymbol localSymbol, SemanticModel semanticModel) { _semanticModel = semanticModel; _localSymbol = localSymbol; } private bool IsReference(SimpleNameSyntax name) { if (name.Identifier.ValueText != _localSymbol.Name) { return false; } var symbol = _semanticModel.GetSymbolInfo(name).Symbol; return symbol != null && symbol.Equals(_localSymbol); } public override SyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node) { // Note - leave this as SyntaxNode for now, we might have already re-written it var newNode = base.VisitAssignmentExpression(node); if (newNode.Kind() == SyntaxKind.SimpleAssignmentExpression) { // It's okay to just look at the text, since we're explicitly looking for an // identifier standing alone, and we know we're in a local's initializer. // The text can only bind to the initializer. var assignment = (AssignmentExpressionSyntax)newNode; var name = assignment.Left.Kind() == SyntaxKind.IdentifierName ? (IdentifierNameSyntax)assignment.Left : null; if (name != null && IsReference(name)) { return assignment.Right; } } return newNode; } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { if (IsReference(node)) { if (node.Parent is AssignmentExpressionSyntax assignmentExpression) { if (assignmentExpression.IsCompoundAssignExpression() && assignmentExpression.Left == node) { return node.Update(node.Identifier.WithAdditionalAnnotations(CreateConflictAnnotation())); } } } return base.VisitIdentifierName(node); } public override SyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { var newNode = base.VisitParenthesizedExpression(node); if (node != newNode && newNode.Kind() == SyntaxKind.ParenthesizedExpression) { return newNode.WithAdditionalAnnotations(Simplifier.Annotation); } return newNode; } public static ExpressionSyntax Visit(ExpressionSyntax initializer, ILocalSymbol local, SemanticModel semanticModel) { var simplifier = new InitializerRewriter(local, semanticModel); return (ExpressionSyntax)simplifier.Visit(initializer); } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/AbstractRenameTagger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract class AbstractRenameTagger<T> : ITagger<T>, IDisposable where T : ITag { private readonly ITextBuffer _buffer; private readonly InlineRenameService _renameService; private InlineRenameSession.OpenTextBufferManager _bufferManager; private IEnumerable<RenameTrackingSpan> _currentSpans; protected AbstractRenameTagger(ITextBuffer buffer, InlineRenameService renameService) { _buffer = buffer; _renameService = renameService; _renameService.ActiveSessionChanged += OnActiveSessionChanged; if (_renameService.ActiveSession != null) { AttachToSession(_renameService.ActiveSession); } } private void OnActiveSessionChanged(object sender, InlineRenameService.ActiveSessionChangedEventArgs e) { if (e.PreviousSession != null) { DetachFromSession(); } if (_renameService.ActiveSession != null) { AttachToSession(_renameService.ActiveSession); } } private void AttachToSession(InlineRenameSession session) { if (session.TryGetBufferManager(_buffer, out _bufferManager)) { _bufferManager.SpansChanged += OnSpansChanged; OnSpansChanged(); } } private void DetachFromSession() { if (_bufferManager != null) { RaiseTagsChangedForEntireBuffer(); _bufferManager.SpansChanged -= OnSpansChanged; _bufferManager = null; _currentSpans = null; } } private void OnSpansChanged() { _currentSpans = _bufferManager.GetRenameTrackingSpans(); RaiseTagsChangedForEntireBuffer(); } private void RaiseTagsChangedForEntireBuffer() => TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(_buffer.CurrentSnapshot.GetFullSpan())); public void Dispose() { _renameService.ActiveSessionChanged -= OnActiveSessionChanged; if (_renameService.ActiveSession != null) { DetachFromSession(); } } public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public IEnumerable<ITagSpan<T>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_renameService.ActiveSession == null) { yield break; } var renameSpans = _currentSpans; if (renameSpans != null) { var snapshot = spans.First().Snapshot; foreach (var renameSpan in renameSpans) { var span = renameSpan.TrackingSpan.GetSpan(snapshot); if (spans.OverlapsWith(span)) { if (TryCreateTagSpan(span, renameSpan.Type, out var tagSpan)) { yield return tagSpan; } } } } } protected abstract bool TryCreateTagSpan(SnapshotSpan span, RenameSpanKind type, out TagSpan<T> tagSpan); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract class AbstractRenameTagger<T> : ITagger<T>, IDisposable where T : ITag { private readonly ITextBuffer _buffer; private readonly InlineRenameService _renameService; private InlineRenameSession.OpenTextBufferManager _bufferManager; private IEnumerable<RenameTrackingSpan> _currentSpans; protected AbstractRenameTagger(ITextBuffer buffer, InlineRenameService renameService) { _buffer = buffer; _renameService = renameService; _renameService.ActiveSessionChanged += OnActiveSessionChanged; if (_renameService.ActiveSession != null) { AttachToSession(_renameService.ActiveSession); } } private void OnActiveSessionChanged(object sender, InlineRenameService.ActiveSessionChangedEventArgs e) { if (e.PreviousSession != null) { DetachFromSession(); } if (_renameService.ActiveSession != null) { AttachToSession(_renameService.ActiveSession); } } private void AttachToSession(InlineRenameSession session) { if (session.TryGetBufferManager(_buffer, out _bufferManager)) { _bufferManager.SpansChanged += OnSpansChanged; OnSpansChanged(); } } private void DetachFromSession() { if (_bufferManager != null) { RaiseTagsChangedForEntireBuffer(); _bufferManager.SpansChanged -= OnSpansChanged; _bufferManager = null; _currentSpans = null; } } private void OnSpansChanged() { _currentSpans = _bufferManager.GetRenameTrackingSpans(); RaiseTagsChangedForEntireBuffer(); } private void RaiseTagsChangedForEntireBuffer() => TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(_buffer.CurrentSnapshot.GetFullSpan())); public void Dispose() { _renameService.ActiveSessionChanged -= OnActiveSessionChanged; if (_renameService.ActiveSession != null) { DetachFromSession(); } } public event EventHandler<SnapshotSpanEventArgs> TagsChanged; public IEnumerable<ITagSpan<T>> GetTags(NormalizedSnapshotSpanCollection spans) { if (_renameService.ActiveSession == null) { yield break; } var renameSpans = _currentSpans; if (renameSpans != null) { var snapshot = spans.First().Snapshot; foreach (var renameSpan in renameSpans) { var span = renameSpan.TrackingSpan.GetSpan(snapshot); if (spans.OverlapsWith(span)) { if (TryCreateTagSpan(span, renameSpan.Type, out var tagSpan)) { yield return tagSpan; } } } } } protected abstract bool TryCreateTagSpan(SnapshotSpan span, RenameSpanKind type, out TagSpan<T> tagSpan); } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Analyzers/CSharp/CodeFixes/AddAccessibilityModifiers/CSharpAddAccessibilityModifiersCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAccessibilityModifiers), Shared] internal class CSharpAddAccessibilityModifiersCodeFixProvider : AbstractAddAccessibilityModifiersCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAddAccessibilityModifiersCodeFixProvider() { } protected override SyntaxNode MapToDeclarator(SyntaxNode node) { switch (node) { case FieldDeclarationSyntax field: return field.Declaration.Variables[0]; case EventFieldDeclarationSyntax eventField: return eventField.Declaration.Variables[0]; default: return node; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.AddAccessibilityModifiers; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.AddAccessibilityModifiers { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAccessibilityModifiers), Shared] internal class CSharpAddAccessibilityModifiersCodeFixProvider : AbstractAddAccessibilityModifiersCodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpAddAccessibilityModifiersCodeFixProvider() { } protected override SyntaxNode MapToDeclarator(SyntaxNode node) { switch (node) { case FieldDeclarationSyntax field: return field.Declaration.Variables[0]; case EventFieldDeclarationSyntax eventField: return eventField.Declaration.Variables[0]; default: return node; } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Core/Shared/BrowserHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Shared { internal static class BrowserHelper { /// <summary> /// Unique VS session id. /// Internal for testing. /// TODO: Revisit - static non-deterministic data https://github.com/dotnet/roslyn/issues/39415 /// </summary> internal static readonly string EscapedRequestId = Guid.NewGuid().ToString(); private const string BingGetApiUrl = "https://bingdev.cloudapp.net/BingUrl.svc/Get"; private const int BingQueryArgumentMaxLength = 10240; private static bool TryGetWellFormedHttpUri(string? link, [NotNullWhen(true)] out Uri? uri) { uri = null; if (string.IsNullOrWhiteSpace(link) || !Uri.IsWellFormedUriString(link, UriKind.Absolute)) { return false; } var absoluteUri = new Uri(link, UriKind.Absolute); if (absoluteUri.Scheme != Uri.UriSchemeHttp && absoluteUri.Scheme != Uri.UriSchemeHttps) { return false; } uri = absoluteUri; return true; } public static Uri? GetHelpLink(DiagnosticDescriptor descriptor, string language) => GetHelpLink(descriptor.Id, descriptor.GetBingHelpMessage(), language, descriptor.HelpLinkUri); public static Uri? GetHelpLink(DiagnosticData data) => GetHelpLink(data.Id, data.ENUMessageForBingSearch, data.Language, data.HelpLink); private static Uri? GetHelpLink(string diagnosticId, string? title, string? language, string? rawHelpLink) { if (string.IsNullOrWhiteSpace(diagnosticId)) { return null; } if (TryGetWellFormedHttpUri(rawHelpLink, out var link)) { return link; } return new Uri(BingGetApiUrl + "?selectedText=" + EscapeDataString(title) + "&mainLanguage=" + EscapeDataString(language) + "&requestId=" + EscapedRequestId + "&errorCode=" + EscapeDataString(diagnosticId)); } private static string EscapeDataString(string? str) { if (str == null) { return string.Empty; } try { // Uri has limit on string size (32766 characters). return Uri.EscapeDataString(str.Substring(0, Math.Min(str.Length, BingQueryArgumentMaxLength))); } catch (UriFormatException) { return string.Empty; } } public static string? GetHelpLinkToolTip(DiagnosticData data) { var helpLink = GetHelpLink(data); if (helpLink == null) { return null; } return GetHelpLinkToolTip(data.Id, helpLink); } public static string GetHelpLinkToolTip(string diagnosticId, Uri uri) { var strUri = uri.ToString(); var resourceName = strUri.StartsWith(BingGetApiUrl, StringComparison.Ordinal) ? EditorFeaturesResources.Get_help_for_0_from_Bing : EditorFeaturesResources.Get_help_for_0; // We make sure not to use Uri.AbsoluteUri for the url displayed in the tooltip so that the url displayed in the tooltip stays human readable. return string.Format(resourceName, diagnosticId) + "\r\n" + strUri; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.Shared { internal static class BrowserHelper { /// <summary> /// Unique VS session id. /// Internal for testing. /// TODO: Revisit - static non-deterministic data https://github.com/dotnet/roslyn/issues/39415 /// </summary> internal static readonly string EscapedRequestId = Guid.NewGuid().ToString(); private const string BingGetApiUrl = "https://bingdev.cloudapp.net/BingUrl.svc/Get"; private const int BingQueryArgumentMaxLength = 10240; private static bool TryGetWellFormedHttpUri(string? link, [NotNullWhen(true)] out Uri? uri) { uri = null; if (string.IsNullOrWhiteSpace(link) || !Uri.IsWellFormedUriString(link, UriKind.Absolute)) { return false; } var absoluteUri = new Uri(link, UriKind.Absolute); if (absoluteUri.Scheme != Uri.UriSchemeHttp && absoluteUri.Scheme != Uri.UriSchemeHttps) { return false; } uri = absoluteUri; return true; } public static Uri? GetHelpLink(DiagnosticDescriptor descriptor, string language) => GetHelpLink(descriptor.Id, descriptor.GetBingHelpMessage(), language, descriptor.HelpLinkUri); public static Uri? GetHelpLink(DiagnosticData data) => GetHelpLink(data.Id, data.ENUMessageForBingSearch, data.Language, data.HelpLink); private static Uri? GetHelpLink(string diagnosticId, string? title, string? language, string? rawHelpLink) { if (string.IsNullOrWhiteSpace(diagnosticId)) { return null; } if (TryGetWellFormedHttpUri(rawHelpLink, out var link)) { return link; } return new Uri(BingGetApiUrl + "?selectedText=" + EscapeDataString(title) + "&mainLanguage=" + EscapeDataString(language) + "&requestId=" + EscapedRequestId + "&errorCode=" + EscapeDataString(diagnosticId)); } private static string EscapeDataString(string? str) { if (str == null) { return string.Empty; } try { // Uri has limit on string size (32766 characters). return Uri.EscapeDataString(str.Substring(0, Math.Min(str.Length, BingQueryArgumentMaxLength))); } catch (UriFormatException) { return string.Empty; } } public static string? GetHelpLinkToolTip(DiagnosticData data) { var helpLink = GetHelpLink(data); if (helpLink == null) { return null; } return GetHelpLinkToolTip(data.Id, helpLink); } public static string GetHelpLinkToolTip(string diagnosticId, Uri uri) { var strUri = uri.ToString(); var resourceName = strUri.StartsWith(BingGetApiUrl, StringComparison.Ordinal) ? EditorFeaturesResources.Get_help_for_0_from_Bing : EditorFeaturesResources.Get_help_for_0; // We make sure not to use Uri.AbsoluteUri for the url displayed in the tooltip so that the url displayed in the tooltip stays human readable. return string.Format(resourceName, diagnosticId) + "\r\n" + strUri; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Core/InheritanceMargin/AbstractInheritanceMarginService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.InheritanceMargin.InheritanceMarginServiceHelper; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal abstract class AbstractInheritanceMarginService : IInheritanceMarginService { /// <summary> /// Given the syntax nodes to search, /// get all the method, event, property and type declaration syntax nodes. /// </summary> protected abstract ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch); /// <summary> /// Get the token that represents declaration node. /// e.g. Identifier for method/property/event and this keyword for indexer. /// </summary> protected abstract SyntaxToken GetDeclarationToken(SyntaxNode declarationNode); public async ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMemberItemsAsync( Document document, TextSpan spanToSearch, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var allDeclarationNodes = GetMembers(root.DescendantNodes(spanToSearch)); if (allDeclarationNodes.IsEmpty) { return ImmutableArray<InheritanceMarginItem>.Empty; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mappingService = document.Project.Solution.Workspace.Services.GetRequiredService<ISymbolMappingService>(); using var _ = ArrayBuilder<(SymbolKey symbolKey, int lineNumber)>.GetInstance(out var builder); Project? project = null; foreach (var memberDeclarationNode in allDeclarationNodes) { var member = semanticModel.GetDeclaredSymbol(memberDeclarationNode, cancellationToken); if (member == null || !CanHaveInheritanceTarget(member)) { continue; } // Use mapping service to find correct solution & symbol. (e.g. metadata symbol) var mappingResult = await mappingService.MapSymbolAsync(document, member, cancellationToken).ConfigureAwait(false); if (mappingResult == null) { continue; } // All the symbols here are declared in the same document, they should belong to the same project. // So here it is enough to get the project once. project ??= mappingResult.Project; builder.Add((mappingResult.Symbol.GetSymbolKey(cancellationToken), sourceText.Lines.GetLineFromPosition(GetDeclarationToken(memberDeclarationNode).SpanStart).LineNumber)); } var symbolKeyAndLineNumbers = builder.ToImmutable(); if (symbolKeyAndLineNumbers.IsEmpty || project == null) { return ImmutableArray<InheritanceMarginItem>.Empty; } var solution = project.Solution; var serializedInheritanceMarginItems = await GetInheritanceMemberItemAsync( solution, project.Id, symbolKeyAndLineNumbers, cancellationToken).ConfigureAwait(false); return await serializedInheritanceMarginItems.SelectAsArrayAsync( (serializedItem, _) => InheritanceMarginItem.ConvertAsync(solution, serializedItem, cancellationToken), cancellationToken).ConfigureAwait(false); } private static bool CanHaveInheritanceTarget(ISymbol symbol) { if (symbol is INamedTypeSymbol namedType) { return !symbol.IsStatic && namedType.TypeKind is TypeKind.Interface or TypeKind.Class or TypeKind.Struct; } if (symbol is IEventSymbol or IPropertySymbol or IMethodSymbol { MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation or MethodKind.UserDefinedOperator or MethodKind.Conversion }) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using static Microsoft.CodeAnalysis.InheritanceMargin.InheritanceMarginServiceHelper; namespace Microsoft.CodeAnalysis.InheritanceMargin { internal abstract class AbstractInheritanceMarginService : IInheritanceMarginService { /// <summary> /// Given the syntax nodes to search, /// get all the method, event, property and type declaration syntax nodes. /// </summary> protected abstract ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch); /// <summary> /// Get the token that represents declaration node. /// e.g. Identifier for method/property/event and this keyword for indexer. /// </summary> protected abstract SyntaxToken GetDeclarationToken(SyntaxNode declarationNode); public async ValueTask<ImmutableArray<InheritanceMarginItem>> GetInheritanceMemberItemsAsync( Document document, TextSpan spanToSearch, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var allDeclarationNodes = GetMembers(root.DescendantNodes(spanToSearch)); if (allDeclarationNodes.IsEmpty) { return ImmutableArray<InheritanceMarginItem>.Empty; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mappingService = document.Project.Solution.Workspace.Services.GetRequiredService<ISymbolMappingService>(); using var _ = ArrayBuilder<(SymbolKey symbolKey, int lineNumber)>.GetInstance(out var builder); Project? project = null; foreach (var memberDeclarationNode in allDeclarationNodes) { var member = semanticModel.GetDeclaredSymbol(memberDeclarationNode, cancellationToken); if (member == null || !CanHaveInheritanceTarget(member)) { continue; } // Use mapping service to find correct solution & symbol. (e.g. metadata symbol) var mappingResult = await mappingService.MapSymbolAsync(document, member, cancellationToken).ConfigureAwait(false); if (mappingResult == null) { continue; } // All the symbols here are declared in the same document, they should belong to the same project. // So here it is enough to get the project once. project ??= mappingResult.Project; builder.Add((mappingResult.Symbol.GetSymbolKey(cancellationToken), sourceText.Lines.GetLineFromPosition(GetDeclarationToken(memberDeclarationNode).SpanStart).LineNumber)); } var symbolKeyAndLineNumbers = builder.ToImmutable(); if (symbolKeyAndLineNumbers.IsEmpty || project == null) { return ImmutableArray<InheritanceMarginItem>.Empty; } var solution = project.Solution; var serializedInheritanceMarginItems = await GetInheritanceMemberItemAsync( solution, project.Id, symbolKeyAndLineNumbers, cancellationToken).ConfigureAwait(false); return await serializedInheritanceMarginItems.SelectAsArrayAsync( (serializedItem, _) => InheritanceMarginItem.ConvertAsync(solution, serializedItem, cancellationToken), cancellationToken).ConfigureAwait(false); } private static bool CanHaveInheritanceTarget(ISymbol symbol) { if (symbol is INamedTypeSymbol namedType) { return !symbol.IsStatic && namedType.TypeKind is TypeKind.Interface or TypeKind.Class or TypeKind.Struct; } if (symbol is IEventSymbol or IPropertySymbol or IMethodSymbol { MethodKind: MethodKind.Ordinary or MethodKind.ExplicitInterfaceImplementation or MethodKind.UserDefinedOperator or MethodKind.Conversion }) { return true; } return false; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Compilers/Test/Core/Pe/BrokenStream.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Roslyn.Test.Utilities { internal class BrokenStream : Stream { public enum BreakHowType { ThrowOnSetPosition, ThrowOnWrite, ThrowOnSetLength, CancelOnWrite } public BreakHowType BreakHow; public Exception ThrownException { get; private set; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { if (BreakHow == BreakHowType.ThrowOnSetPosition) { ThrownException = new NotSupportedException(); throw ThrownException; } } } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { if (BreakHow == BreakHowType.ThrowOnSetLength) { ThrownException = new IOException(); throw ThrownException; } } public override void Write(byte[] buffer, int offset, int count) { if (BreakHow == BreakHowType.ThrowOnWrite) { ThrownException = new IOException(); throw ThrownException; } else if (BreakHow == BreakHowType.CancelOnWrite) { ThrownException = new OperationCanceledException(); throw ThrownException; } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/VisualStudio/CSharp/Impl/EditorConfigSettings/BinaryOperatorSpacingOptionsViewModelFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BinaryOperatorSpacingOptionsViewModelFactory() { } public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting) { return new BinaryOperatorSpacingOptionsViewModel(setting); } public bool IsSupported(OptionKey2 key) => key.Option.Type == typeof(BinaryOperatorSpacingOptions); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.CSharp.EditorConfigSettings { [Export(typeof(IEnumSettingViewModelFactory)), Shared] internal class BinaryOperatorSpacingOptionsViewModelFactory : IEnumSettingViewModelFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public BinaryOperatorSpacingOptionsViewModelFactory() { } public IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting) { return new BinaryOperatorSpacingOptionsViewModel(setting); } public bool IsSupported(OptionKey2 key) => key.Option.Type == typeof(BinaryOperatorSpacingOptions); } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/VisualStudio/Core/Def/Implementation/VisualStudioSupportsFeatureService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SuggestionService { internal sealed class VisualStudioSupportsFeatureService { private const string ContainedLanguageMarker = nameof(ContainedLanguageMarker); [ExportWorkspaceService(typeof(ITextBufferSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioTextBufferSupportsFeatureService : ITextBufferSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextBufferSupportsFeatureService() { } public bool SupportsCodeFixes(ITextBuffer textBuffer) { return SupportsCodeFixesWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRefactorings(ITextBuffer textBuffer) { return SupportsRefactoringsWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRename(ITextBuffer textBuffer) { // TS creates generated documents to back script blocks in razor generated files. // These files are opened in the roslyn workspace but are not valid to rename // as they are not proper buffers. So we exclude any buffer that is marked as a contained language. if (textBuffer.Properties.TryGetProperty<bool>(ContainedLanguageMarker, out var markerValue) && markerValue) { return false; } var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { var documentId = workspace.GetDocumentIdInCurrentContext(sourceTextContainer); return SupportsRenameWorker(workspace.CurrentSolution.GetRelatedDocumentIds(documentId)); } return false; } public bool SupportsNavigationToAnyPosition(ITextBuffer textBuffer) => SupportsNavigationToAnyPositionWorker(GetContainedDocumentId(textBuffer)); private static DocumentId GetContainedDocumentId(ITextBuffer textBuffer) { var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace) && workspace is VisualStudioWorkspaceImpl vsWorkspace) { return vsWorkspace.GetDocumentIdInCurrentContext(sourceTextContainer); } return null; } } [ExportWorkspaceService(typeof(IDocumentSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioDocumentSupportsFeatureService : IDocumentSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentSupportsFeatureService() { } public bool SupportsCodeFixes(Document document) => SupportsCodeFixesWorker(document.Id); public bool SupportsRefactorings(Document document) => SupportsRefactoringsWorker(document.Id); public bool SupportsRename(Document document) => SupportsRenameWorker(document.Project.Solution.GetRelatedDocumentIds(document.Id)); public bool SupportsNavigationToAnyPosition(Document document) => SupportsNavigationToAnyPositionWorker(document.Id); } private static bool SupportsCodeFixesWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRefactoringsWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRenameWorker(ImmutableArray<DocumentId> ids) { return ids.Select(id => ContainedDocument.TryGetContainedDocument(id)) .All(cd => cd == null || cd.SupportsRename); } private static bool SupportsNavigationToAnyPositionWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SuggestionService { internal sealed class VisualStudioSupportsFeatureService { private const string ContainedLanguageMarker = nameof(ContainedLanguageMarker); [ExportWorkspaceService(typeof(ITextBufferSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioTextBufferSupportsFeatureService : ITextBufferSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioTextBufferSupportsFeatureService() { } public bool SupportsCodeFixes(ITextBuffer textBuffer) { return SupportsCodeFixesWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRefactorings(ITextBuffer textBuffer) { return SupportsRefactoringsWorker(GetContainedDocumentId(textBuffer)); } public bool SupportsRename(ITextBuffer textBuffer) { // TS creates generated documents to back script blocks in razor generated files. // These files are opened in the roslyn workspace but are not valid to rename // as they are not proper buffers. So we exclude any buffer that is marked as a contained language. if (textBuffer.Properties.TryGetProperty<bool>(ContainedLanguageMarker, out var markerValue) && markerValue) { return false; } var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace)) { var documentId = workspace.GetDocumentIdInCurrentContext(sourceTextContainer); return SupportsRenameWorker(workspace.CurrentSolution.GetRelatedDocumentIds(documentId)); } return false; } public bool SupportsNavigationToAnyPosition(ITextBuffer textBuffer) => SupportsNavigationToAnyPositionWorker(GetContainedDocumentId(textBuffer)); private static DocumentId GetContainedDocumentId(ITextBuffer textBuffer) { var sourceTextContainer = textBuffer.AsTextContainer(); if (Workspace.TryGetWorkspace(sourceTextContainer, out var workspace) && workspace is VisualStudioWorkspaceImpl vsWorkspace) { return vsWorkspace.GetDocumentIdInCurrentContext(sourceTextContainer); } return null; } } [ExportWorkspaceService(typeof(IDocumentSupportsFeatureService), ServiceLayer.Host), Shared] private class VisualStudioDocumentSupportsFeatureService : IDocumentSupportsFeatureService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioDocumentSupportsFeatureService() { } public bool SupportsCodeFixes(Document document) => SupportsCodeFixesWorker(document.Id); public bool SupportsRefactorings(Document document) => SupportsRefactoringsWorker(document.Id); public bool SupportsRename(Document document) => SupportsRenameWorker(document.Project.Solution.GetRelatedDocumentIds(document.Id)); public bool SupportsNavigationToAnyPosition(Document document) => SupportsNavigationToAnyPositionWorker(document.Id); } private static bool SupportsCodeFixesWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRefactoringsWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; private static bool SupportsRenameWorker(ImmutableArray<DocumentId> ids) { return ids.Select(id => ContainedDocument.TryGetContainedDocument(id)) .All(cd => cd == null || cd.SupportsRename); } private static bool SupportsNavigationToAnyPositionWorker(DocumentId id) => ContainedDocument.TryGetContainedDocument(id) == null; } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./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
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/CSharp/Portable/SemanticModelReuse/CSharpSemanticModelReuseLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.SemanticModelReuse; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SemanticModelReuse { [ExportLanguageService(typeof(ISemanticModelReuseLanguageService), LanguageNames.CSharp), Shared] internal class CSharpSemanticModelReuseLanguageService : AbstractSemanticModelReuseLanguageService< MemberDeclarationSyntax, BaseMethodDeclarationSyntax, BasePropertyDeclarationSyntax, AccessorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSemanticModelReuseLanguageService() { } protected override ISyntaxFacts SyntaxFacts => CSharpSyntaxFacts.Instance; protected override BasePropertyDeclarationSyntax GetBasePropertyDeclaration(AccessorDeclarationSyntax accessor) { Contract.ThrowIfFalse(accessor.Parent is AccessorListSyntax); Contract.ThrowIfFalse(accessor.Parent.Parent is BasePropertyDeclarationSyntax); return (BasePropertyDeclarationSyntax)accessor.Parent.Parent; } protected override SyntaxList<AccessorDeclarationSyntax> GetAccessors(BasePropertyDeclarationSyntax baseProperty) => baseProperty.AccessorList!.Accessors; public override SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node) { for (SyntaxNode? previous = null, current = node; current != null; previous = current, current = current.Parent) { // These are the exact types that SemanticModel.TryGetSpeculativeSemanticModelForMethodBody accepts. if (current is BaseMethodDeclarationSyntax baseMethod) return previous != null && baseMethod.Body == previous ? baseMethod : null; if (current is AccessorDeclarationSyntax accessor) return previous != null && accessor.Body == previous ? accessor : null; } return null; } protected override async Task<SemanticModel?> TryGetSpeculativeSemanticModelWorkerAsync( SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken) { var previousRoot = await previousSemanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await currentBodyNode.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var previousBodyNode = GetPreviousBodyNode(previousRoot, currentRoot, currentBodyNode); if (previousBodyNode is BaseMethodDeclarationSyntax previousBaseMethod && currentBodyNode is BaseMethodDeclarationSyntax currentBaseMethod && previousBaseMethod.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousBaseMethod.Body.SpanStart, currentBaseMethod, out var speculativeModel)) { return speculativeModel; } if (previousBodyNode is AccessorDeclarationSyntax previousAccessorDeclaration && currentBodyNode is AccessorDeclarationSyntax currentAccessorDeclaration && previousAccessorDeclaration.Body != null && previousSemanticModel.TryGetSpeculativeSemanticModelForMethodBody(previousAccessorDeclaration.Body.SpanStart, currentAccessorDeclaration, out speculativeModel)) { return speculativeModel; } return null; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Analyzers/CSharp/Tests/AddBraces/AddBracesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddBraces { public partial class AddBracesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddBracesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAddBracesDiagnosticAnalyzer(), new CSharpAddBracesCodeFixProvider()); [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForIfWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|if|] (true) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForElseWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { if (true) { return; } [|else|] { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForElseWithChildIf(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { if (true) return; [|else|] if (false) return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForForWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForForEachWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|foreach|] (var c in ""test"") { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForWhileWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|while|] (true) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForDoWhileWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|do|] { return; } while (true); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForUsingWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|using|] (var f = new Fizz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForUsingWithChildUsing(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|using|] (var f = new Fizz()) using (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForLockWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { var str = ""test""; [|lock|] (str) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForLockWithChildLock(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; [|lock|] (str1) lock (str2) return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForFixedWithChildFixed(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { unsafe static void Main() { [|fixed|] (int* p = null) fixed (int* q = null) { } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForFixedWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @"class Program { unsafe static void Main() { fixed (int* p = null) [|fixed|] (int* q = null) return; } }", @"class Program { unsafe static void Main() { fixed (int* p = null) fixed (int* q = null) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|if|] (true) return; } }", @" class Program { static void Main() { if (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForElseWithoutBracesButHasContextBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { return; } [|else|] return; } }", @" class Program { static void Main() { if (true) { return; } else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) return; [|else|] return; } }", @" class Program { static void Main() { if (true) return; else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForStandaloneElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|else|] return; } }", @" class Program { static void Main() { {} else return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) return; else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) return; else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) if (true) // This multiline statement does not directly impact the other nested statement return; else return; else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) if (true) // This multiline statement does not directly impact the other nested statement return; else return; else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) return; else return; } else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) { if (true) return; else return; } else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext3(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { [|if|] (true) return; else return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) { return; } else return; } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext4(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) return; [|else|] return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) return; else { return; } } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } #pragma warning disable CA1200 // Avoid using cref tags with a prefix - Remove the suppression when https://github.com/dotnet/roslyn/issues/42611 is fixed. /// <summary> /// Verifies that the use of braces in a construct nested within the true portion of an <c>if</c> statement does /// not trigger the multiline behavior the <c>else</c> clause of a containing stetemnet for /// <see cref="F:Microsoft.CodeAnalysis.CodeStyle.PreferBracesPreference.WhenMultiline"/>. The <c>else</c> clause would only need braces if the true /// portion also used braces (which would be required if the true portion was considered multiline. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext5(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) if (true) { return; } else { return; } [|else|] return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) if (true) { return; } else { return; } else { return; } } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForForWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) if (true) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { if (true) return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces3(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) if (true) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { if (true) return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForForEachWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|foreach|] (var c in ""test"") return; } }", @" class Program { static void Main() { foreach (var c in ""test"") { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForWhileWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|while|] (true) return; } }", @" class Program { static void Main() { while (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true); } }", @" class Program { static void Main() { do { return; } while (true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForDoWhileWithoutBraces2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true); } }", @" class Program { static void Main() { do { return; } while (true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true || true); } }", @" class Program { static void Main() { do { return; } while (true || true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForUsingWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|using|] (var f = new Fizz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForUsingWithoutBracesNestedInUsing(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f = new Fizz()) [|using|] (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) using (var b = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineUsingWithoutBracesNestedInUsing1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f // <-- This multiline condition doesn't trigger a multiline braces requirement when it's the outer 'using' statement = new Fizz()) [|using|] (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f // <-- This multiline condition doesn't trigger a multiline braces requirement when it's the outer 'using' statement = new Fizz()) using (var b = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineUsingWithoutBracesNestedInUsing2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f = new Fizz()) [|using|] (var b // <-- This multiline condition triggers a multiline braces requirement because it's the inner 'using' statement = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) using (var b // <-- This multiline condition triggers a multiline braces requirement because it's the inner 'using' statement = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForLockWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { var str = ""test""; [|lock|] (str) return; } }", @" class Program { static void Main() { var str = ""test""; lock (str) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForLockWithoutBracesNestedInLock(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; lock (str1) [|lock|] (str2) // VS thinks this should be indented one more level return; } }", @" class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; lock (str1) lock (str2) // VS thinks this should be indented one more level { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfWhenIntercedingDirectiveBefore(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { #if test [|if (true)|] #endif return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfWithIntercedingDirectiveAfter(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { [|if (true)|] #if test return; #endif } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfElseWithIntercedingDirectiveInBoth(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { [|if (true) #if test return; else|] #endif return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForIfWithIntercedingDirectiveInElseAroundIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) return; else|] #endif return; } }", @" #define test class Program { static void Main() { #if test if (true) { return; } else #endif return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForElseWithIntercedingDirectiveInIfAroundElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) #if test return; else|] return; #endif } }", @" #define test class Program { static void Main() { if (true) #if test return; else { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForElseWithIntercedingDirectiveInIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) #endif return; else|] return; } }", @" #define test class Program { static void Main() { #if test if (true) #endif return; else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForIfWithIntercedingDirectiveInElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) return; else|] #if test return; #endif } }", @" #define test class Program { static void Main() { if (true) { return; } else #if test return; #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfElseWithDirectiveAroundIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) return; #endif else|] { return; } } }", @" #define test class Program { static void Main() { #if test if (true) { return; } #endif else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfElseWithDirectiveAroundElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) { return; } #if test else|] return; #endif } }", @" #define test class Program { static void Main() { if (true) { return; } #if test else { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfWithoutIntercedingDirective(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test #endif [|if (true)|] return; } }", @" #define test class Program { static void Main() { #if test #endif if (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfWithDirectiveAfterEmbeddedStatement(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true)|] return; #if test #endif } }", @" #define test class Program { static void Main() { if (true) { return; } #if test #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForInnerNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|while (true) #if test if (true)|] return; #endif } }", @" #define test class Program { static void Main() { while (true) #if test if (true) { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForOuterNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|while (true) #if test if (true)|] #endif return; } }", @" #define test class Program { static void Main() { while (true) { #if test if (true) #endif return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } private async Task TestAsync(string initialMarkup, string expectedMarkup, PreferBracesPreference bracesPreference, bool expectDiagnostic) { if (expectDiagnostic) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent)); } else { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddBraces { public partial class AddBracesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public AddBracesTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpAddBracesDiagnosticAnalyzer(), new CSharpAddBracesCodeFixProvider()); [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForIfWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|if|] (true) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForElseWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { if (true) { return; } [|else|] { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForElseWithChildIf(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { if (true) return; [|else|] if (false) return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForForWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForForEachWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|foreach|] (var c in ""test"") { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForWhileWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|while|] (true) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForDoWhileWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|do|] { return; } while (true); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForUsingWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|using|] (var f = new Fizz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForUsingWithChildUsing(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { [|using|] (var f = new Fizz()) using (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForLockWithBraces(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { var str = ""test""; [|lock|] (str) { return; } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForLockWithChildLock(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; [|lock|] (str1) lock (str2) return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] public async Task DoNotFireForFixedWithChildFixed(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @"class Program { unsafe static void Main() { [|fixed|] (int* p = null) fixed (int* q = null) { } } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForFixedWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @"class Program { unsafe static void Main() { fixed (int* p = null) [|fixed|] (int* q = null) return; } }", @"class Program { unsafe static void Main() { fixed (int* p = null) fixed (int* q = null) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|if|] (true) return; } }", @" class Program { static void Main() { if (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForElseWithoutBracesButHasContextBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { return; } [|else|] return; } }", @" class Program { static void Main() { if (true) { return; } else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) return; [|else|] return; } }", @" class Program { static void Main() { if (true) return; else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForStandaloneElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|else|] return; } }", @" class Program { static void Main() { {} else return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) return; else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) return; else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) if (true) // This multiline statement does not directly impact the other nested statement return; else return; else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) if (true) // This multiline statement does not directly impact the other nested statement return; else return; else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) return; else return; } else [|if|] (false) return; } }", @" class Program { static void Main() { if (true) { if (true) return; else return; } else if (false) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext3(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { [|if|] (true) return; else return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) { return; } else return; } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext4(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) return; [|else|] return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) return; else { return; } } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } #pragma warning disable CA1200 // Avoid using cref tags with a prefix - Remove the suppression when https://github.com/dotnet/roslyn/issues/42611 is fixed. /// <summary> /// Verifies that the use of braces in a construct nested within the true portion of an <c>if</c> statement does /// not trigger the multiline behavior the <c>else</c> clause of a containing stetemnet for /// <see cref="F:Microsoft.CodeAnalysis.CodeStyle.PreferBracesPreference.WhenMultiline"/>. The <c>else</c> clause would only need braces if the true /// portion also used braces (which would be required if the true portion was considered multiline. /// </summary> #pragma warning restore CA1200 // Avoid using cref tags with a prefix [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForIfNestedInElseWithoutBracesWithMultilineContext5(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { if (true) { if (true) if (true) { return; } else { return; } [|else|] return; } else if (false) return; } }", @" class Program { static void Main() { if (true) { if (true) if (true) { return; } else { return; } else { return; } } else if (false) return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForForWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) if (true) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { if (true) return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineForWithoutBraces3(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|for|] (var i = 0; i < 5; i++) if (true) return; } }", @" class Program { static void Main() { for (var i = 0; i < 5; i++) { if (true) return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForForEachWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|foreach|] (var c in ""test"") return; } }", @" class Program { static void Main() { foreach (var c in ""test"") { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForWhileWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|while|] (true) return; } }", @" class Program { static void Main() { while (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true); } }", @" class Program { static void Main() { do { return; } while (true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForDoWhileWithoutBraces2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true); } }", @" class Program { static void Main() { do { return; } while (true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineDoWhileWithoutBraces1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|do|] return; while (true || true); } }", @" class Program { static void Main() { do { return; } while (true || true); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForUsingWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { [|using|] (var f = new Fizz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForUsingWithoutBracesNestedInUsing(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f = new Fizz()) [|using|] (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) using (var b = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineUsingWithoutBracesNestedInUsing1(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f // <-- This multiline condition doesn't trigger a multiline braces requirement when it's the outer 'using' statement = new Fizz()) [|using|] (var b = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f // <-- This multiline condition doesn't trigger a multiline braces requirement when it's the outer 'using' statement = new Fizz()) using (var b = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForMultilineUsingWithoutBracesNestedInUsing2(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { using (var f = new Fizz()) [|using|] (var b // <-- This multiline condition triggers a multiline braces requirement because it's the inner 'using' statement = new Buzz()) return; } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", @" class Program { static void Main() { using (var f = new Fizz()) using (var b // <-- This multiline condition triggers a multiline braces requirement because it's the inner 'using' statement = new Buzz()) { return; } } } class Fizz : IDisposable { public void Dispose() { throw new NotImplementedException(); } } class Buzz : IDisposable { public void Dispose() { throw new NotImplementedException(); } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForLockWithoutBraces(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { var str = ""test""; [|lock|] (str) return; } }", @" class Program { static void Main() { var str = ""test""; lock (str) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] public async Task FireForLockWithoutBracesNestedInLock(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; lock (str1) [|lock|] (str2) // VS thinks this should be indented one more level return; } }", @" class Program { static void Main() { var str1 = ""test""; var str2 = ""test""; lock (str1) lock (str2) // VS thinks this should be indented one more level { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfWhenIntercedingDirectiveBefore(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { #if test [|if (true)|] #endif return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfWithIntercedingDirectiveAfter(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { [|if (true)|] #if test return; #endif } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None)] [InlineData((int)PreferBracesPreference.WhenMultiline)] [InlineData((int)PreferBracesPreference.Always)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task DoNotFireForIfElseWithIntercedingDirectiveInBoth(int bracesPreference) { await TestMissingInRegularAndScriptAsync( @" #define test class Program { static void Main() { [|if (true) #if test return; else|] #endif return; } }", new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, (PreferBracesPreference)bracesPreference, NotificationOption2.Silent))); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForIfWithIntercedingDirectiveInElseAroundIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) return; else|] #endif return; } }", @" #define test class Program { static void Main() { #if test if (true) { return; } else #endif return; } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForElseWithIntercedingDirectiveInIfAroundElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) #if test return; else|] return; #endif } }", @" #define test class Program { static void Main() { if (true) #if test return; else { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForElseWithIntercedingDirectiveInIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) #endif return; else|] return; } }", @" #define test class Program { static void Main() { #if test if (true) #endif return; else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task OnlyFireForIfWithIntercedingDirectiveInElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) return; else|] #if test return; #endif } }", @" #define test class Program { static void Main() { if (true) { return; } else #if test return; #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfElseWithDirectiveAroundIf(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test [|if (true) return; #endif else|] { return; } } }", @" #define test class Program { static void Main() { #if test if (true) { return; } #endif else { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfElseWithDirectiveAroundElse(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true) { return; } #if test else|] return; #endif } }", @" #define test class Program { static void Main() { if (true) { return; } #if test else { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfWithoutIntercedingDirective(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { #if test #endif [|if (true)|] return; } }", @" #define test class Program { static void Main() { #if test #endif if (true) { return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForIfWithDirectiveAfterEmbeddedStatement(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|if (true)|] return; #if test #endif } }", @" #define test class Program { static void Main() { if (true) { return; } #if test #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, false)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForInnerNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|while (true) #if test if (true)|] return; #endif } }", @" #define test class Program { static void Main() { while (true) #if test if (true) { return; } #endif } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)] [InlineData((int)PreferBracesPreference.None, false)] [InlineData((int)PreferBracesPreference.WhenMultiline, true)] [InlineData((int)PreferBracesPreference.Always, true)] [WorkItem(32480, "https://github.com/dotnet/roslyn/issues/32480")] public async Task FireForOuterNestedStatementWhenDirectiveEntirelyInside(int bracesPreference, bool expectDiagnostic) { await TestAsync( @" #define test class Program { static void Main() { [|while (true) #if test if (true)|] #endif return; } }", @" #define test class Program { static void Main() { while (true) { #if test if (true) #endif return; } } }", (PreferBracesPreference)bracesPreference, expectDiagnostic); } private async Task TestAsync(string initialMarkup, string expectedMarkup, PreferBracesPreference bracesPreference, bool expectDiagnostic) { if (expectDiagnostic) { await TestInRegularAndScriptAsync(initialMarkup, expectedMarkup, options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent)); } else { await TestMissingInRegularAndScriptAsync(initialMarkup, new TestParameters(options: Option(CSharpCodeStyleOptions.PreferBraces, bracesPreference, NotificationOption2.Silent))); } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/CSharp/Portable/ConvertIfToSwitch/CSharpConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch { internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider { private sealed class CSharpAnalyzer : Analyzer { public CSharpAnalyzer(ISyntaxFacts syntaxFacts, Feature features) : base(syntaxFacts, features) { } public override bool HasUnreachableEndPoint(IOperation operation) => !operation.SemanticModel.AnalyzeControlFlow(operation.Syntax).EndPointIsReachable; // We do not offer a fix if the if-statement contains a break-statement, e.g. // // while (...) // { // if (...) { // break; // } // } // // When the 'break' moves into the switch, it will have different flow control impact. public override bool CanConvert(IConditionalOperation operation) => !operation.SemanticModel.AnalyzeControlFlow(operation.Syntax).ExitPoints.Any(n => n.IsKind(SyntaxKind.BreakStatement)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.CSharp.ConvertIfToSwitch { internal sealed partial class CSharpConvertIfToSwitchCodeRefactoringProvider { private sealed class CSharpAnalyzer : Analyzer { public CSharpAnalyzer(ISyntaxFacts syntaxFacts, Feature features) : base(syntaxFacts, features) { } public override bool HasUnreachableEndPoint(IOperation operation) => !operation.SemanticModel.AnalyzeControlFlow(operation.Syntax).EndPointIsReachable; // We do not offer a fix if the if-statement contains a break-statement, e.g. // // while (...) // { // if (...) { // break; // } // } // // When the 'break' moves into the switch, it will have different flow control impact. public override bool CanConvert(IConditionalOperation operation) => !operation.SemanticModel.AnalyzeControlFlow(operation.Syntax).ExitPoints.Any(n => n.IsKind(SyntaxKind.BreakStatement)); } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/NamingStyle.WordSpanEnumerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NamingStyles { internal partial struct NamingStyle { private struct WordSpanEnumerator { private readonly string _name; private readonly TextSpan _nameSpan; private readonly string _wordSeparator; public WordSpanEnumerator(string name, TextSpan nameSpan, string wordSeparator) { Debug.Assert(nameSpan.Length > 0); _name = name; _nameSpan = nameSpan; _wordSeparator = wordSeparator; Current = new TextSpan(nameSpan.Start, 0); } public TextSpan Current { get; private set; } public bool MoveNext() { if (_wordSeparator == "") { // No separator. So only ever return a single word if (Current.Length == 0) { Current = _nameSpan; return true; } else { return false; } } while (true) { var nextWordSeparator = _name.IndexOf(_wordSeparator, Current.End); if (nextWordSeparator == Current.End) { // We're right at the word separator. Skip it and continue searching. Current = new TextSpan(Current.End + _wordSeparator.Length, 0); continue; } // If didn't find a word separator, it's as if the next word separator is at the end of name span. if (nextWordSeparator < 0) { nextWordSeparator = _nameSpan.End; } // If we've walked past the _nameSpan just immediately stop. There are no more words to return. if (Current.End > _nameSpan.End) { return false; } // found a separator in front of us. Note: it may be in our suffix portion. // So use the min of the separator position and our end position. Current = TextSpan.FromBounds(Current.End, Math.Min(_nameSpan.End, nextWordSeparator)); break; } return Current.Length > 0 && Current.End <= _nameSpan.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. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NamingStyles { internal partial struct NamingStyle { private struct WordSpanEnumerator { private readonly string _name; private readonly TextSpan _nameSpan; private readonly string _wordSeparator; public WordSpanEnumerator(string name, TextSpan nameSpan, string wordSeparator) { Debug.Assert(nameSpan.Length > 0); _name = name; _nameSpan = nameSpan; _wordSeparator = wordSeparator; Current = new TextSpan(nameSpan.Start, 0); } public TextSpan Current { get; private set; } public bool MoveNext() { if (_wordSeparator == "") { // No separator. So only ever return a single word if (Current.Length == 0) { Current = _nameSpan; return true; } else { return false; } } while (true) { var nextWordSeparator = _name.IndexOf(_wordSeparator, Current.End); if (nextWordSeparator == Current.End) { // We're right at the word separator. Skip it and continue searching. Current = new TextSpan(Current.End + _wordSeparator.Length, 0); continue; } // If didn't find a word separator, it's as if the next word separator is at the end of name span. if (nextWordSeparator < 0) { nextWordSeparator = _nameSpan.End; } // If we've walked past the _nameSpan just immediately stop. There are no more words to return. if (Current.End > _nameSpan.End) { return false; } // found a separator in front of us. Note: it may be in our suffix portion. // So use the min of the separator position and our end position. Current = TextSpan.FromBounds(Current.End, Math.Min(_nameSpan.End, nextWordSeparator)); break; } return Current.Length > 0 && Current.End <= _nameSpan.End; } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/Core/Portable/Workspace/Solution/Document.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public class Document : TextDocument { /// <summary> /// A cached reference to the <see cref="SemanticModel"/>. /// </summary> private WeakReference<SemanticModel>? _model; /// <summary> /// A cached task that can be returned once the tree has already been created. This is only set if <see cref="SupportsSyntaxTree"/> returns true, /// so the inner value can be non-null. /// </summary> private Task<SyntaxTree>? _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state, TextDocumentKind.Document) { } internal DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind => DocumentState.SourceCodeKind; /// <summary> /// True if the info of the document change (name, folders, file path; not the content) /// </summary> internal override bool HasInfoChanged(TextDocument otherTextDocument) { var otherDocument = otherTextDocument as Document ?? throw new ArgumentException($"{nameof(otherTextDocument)} isn't a regular document.", nameof(otherTextDocument)); return base.HasInfoChanged(otherDocument) || DocumentState.SourceCodeKind != otherDocument.SourceCodeKind; } [Obsolete("Use TextDocument.HasTextChanged")] internal bool HasTextChanged(Document otherDocument) => HasTextChanged(otherDocument, ignoreUnchangeableDocument: false); /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; return true; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default; if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) => DocumentState.TryGetTopLevelChangeTextVersion(out version); /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <see langword="false"/> then these methods will return <see langword="null"/> instead. /// </summary> public bool SupportsSyntaxTree => DocumentState.SupportsSyntaxTree; /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <see langword="false"/> then that method will return <see langword="null"/> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> /// <returns> /// The returned syntax tree can be <see langword="null"/> if the <see cref="SupportsSyntaxTree"/> returns <see /// langword="false"/>. This function may cause computation to occur the first time it is called, but will return /// a cached result every subsequent time. <see cref="SyntaxTree"/>'s can hold onto their roots lazily. So calls /// to <see cref="SyntaxTree.GetRoot"/> or <see cref="SyntaxTree.GetRootAsync"/> may end up causing computation /// to occur at that point. /// </returns> public Task<SyntaxTree?> GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Null<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // do it async for real. // GetSyntaxTreeAsync returns a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask()!; } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot([NotNullWhen(returnValue: true)] out SyntaxNode? root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <returns> /// The returned <see cref="SyntaxNode"/> will be <see langword="null"/> if <see /// cref="SupportsSyntaxTree"/> returns <see langword="false"/>. This function will return /// the same value if called multiple times. /// </returns> public async Task<SyntaxNode?> GetSyntaxRootAsync(CancellationToken cancellationToken = default) { if (!this.SupportsSyntaxTree) { return null; } var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode? GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken)!; return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel([NotNullWhen(returnValue: true)] out SemanticModel? semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> /// <returns> /// The returned <see cref="SemanticModel"/> may be <see langword="null"/> if <see /// cref="SupportsSemanticModel"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public async Task<SemanticModel?> GetSemanticModelAsync(CancellationToken cancellationToken = default) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = (await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false))!; var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // It looks like someone has set it. Try to reuse same semantic model, or assign the new model if that // fails. The lock is required since there is no compare-and-set primitive for WeakReference<T>. lock (original) { if (original.TryGetTarget(out semanticModel)) { return semanticModel; } original.SetTarget(result); return result; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) => this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) => this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) => this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified name. /// </summary> public Document WithName(string name) => this.Project.Solution.WithDocumentName(this.Id, name).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified folders. /// </summary> public Document WithFolders(IEnumerable<string> folders) => this.Project.Solution.WithDocumentFolders(this.Id, folders).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified file path. /// </summary> /// <param name="filePath"></param> // TODO (https://github.com/dotnet/roslyn/issues/37125): Solution.WithDocumentFilePath will throw if // filePath is null, but it's odd because we *do* support null file paths. Why can't you switch a // document back to null? public Document WithFilePath(string filePath) => this.Project.Solution.WithDocumentFilePath(this.Id, filePath).GetDocument(this.Id)!; /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { var textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); RoslynDebug.Assert(oldTree is object); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal virtual Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocument(this.Id, cancellationToken); return newSolution.GetDocument(this.Id)!; } else { return this; } } private string GetDebuggerDisplay() => this.Name; private AsyncLazy<DocumentOptionSet>? _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default) => GetOptionsAsync(Project.Solution.Options, cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", AllowCaptures = false)] internal Task<DocumentOptionSet> GetOptionsAsync(OptionSet solutionOptions, CancellationToken cancellationToken) { // TODO: we have this workaround since Solution.Options is not actually snapshot but just return Workspace.Options which violate snapshot model. // this doesn't validate whether same optionset is given to invalidate the cache or not. this is not new since existing implementation // also didn't check whether Workspace.Option is same as before or not. all weird-ness come from the root cause of Solution.Options violating // snapshot model. once that is fixed, we can remove this workaround - https://github.com/dotnet/roslyn/issues/19284 if (_cachedOptions == null) { InitializeCachedOptions(solutionOptions); } Contract.ThrowIfNull(_cachedOptions); return _cachedOptions.GetValueAsync(cancellationToken); } private void InitializeCachedOptions(OptionSet solutionOptions) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var documentOptionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, solutionOptions, c).ConfigureAwait(false); return new DocumentOptionSet(documentOptionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } internal Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsAsync(CancellationToken cancellationToken) { var projectFilePath = Project.FilePath; // We need to work out path to this document. Documents may not have a "real" file path if they're something created // as a part of a code action, but haven't been written to disk yet. string? effectiveFilePath = null; if (FilePath != null) { effectiveFilePath = FilePath; } else if (Name != null && projectFilePath != null) { var projectPath = PathUtilities.GetDirectoryName(projectFilePath); if (!RoslynString.IsNullOrEmpty(projectPath) && PathUtilities.GetDirectoryName(projectFilePath) is string directory) { effectiveFilePath = PathUtilities.CombinePathsUnchecked(directory, Name); } } if (effectiveFilePath != null) { return Project.State.GetAnalyzerOptionsForPathAsync(effectiveFilePath, cancellationToken); } else { // Really no idea where this is going, so bail // TODO: use AnalyzerConfigOptions.EmptyDictionary, since we don't have a public dictionary return Task.FromResult(ImmutableDictionary.Create<string, string>(AnalyzerConfigOptions.KeyComparer)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public class Document : TextDocument { /// <summary> /// A cached reference to the <see cref="SemanticModel"/>. /// </summary> private WeakReference<SemanticModel>? _model; /// <summary> /// A cached task that can be returned once the tree has already been created. This is only set if <see cref="SupportsSyntaxTree"/> returns true, /// so the inner value can be non-null. /// </summary> private Task<SyntaxTree>? _syntaxTreeResultTask; internal Document(Project project, DocumentState state) : base(project, state, TextDocumentKind.Document) { } internal DocumentState DocumentState => (DocumentState)State; /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind => DocumentState.SourceCodeKind; /// <summary> /// True if the info of the document change (name, folders, file path; not the content) /// </summary> internal override bool HasInfoChanged(TextDocument otherTextDocument) { var otherDocument = otherTextDocument as Document ?? throw new ArgumentException($"{nameof(otherTextDocument)} isn't a regular document.", nameof(otherTextDocument)); return base.HasInfoChanged(otherDocument) || DocumentState.SourceCodeKind != otherDocument.SourceCodeKind; } [Obsolete("Use TextDocument.HasTextChanged")] internal bool HasTextChanged(Document otherDocument) => HasTextChanged(otherDocument, ignoreUnchangeableDocument: false); /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree([NotNullWhen(returnValue: true)] out SyntaxTree? syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; return true; } if (!DocumentState.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default; if (!this.TryGetTextVersion(out var textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) => DocumentState.TryGetTopLevelChangeTextVersion(out version); /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <see langword="false"/> then these methods will return <see langword="null"/> instead. /// </summary> public bool SupportsSyntaxTree => DocumentState.SupportsSyntaxTree; /// <summary> /// <see langword="true"/> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <see langword="false"/> then that method will return <see langword="null"/> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> /// <returns> /// The returned syntax tree can be <see langword="null"/> if the <see cref="SupportsSyntaxTree"/> returns <see /// langword="false"/>. This function may cause computation to occur the first time it is called, but will return /// a cached result every subsequent time. <see cref="SyntaxTree"/>'s can hold onto their roots lazily. So calls /// to <see cref="SyntaxTree.GetRoot"/> or <see cref="SyntaxTree.GetRootAsync"/> may end up causing computation /// to occur at that point. /// </returns> public Task<SyntaxTree?> GetSyntaxTreeAsync(CancellationToken cancellationToken = default) { // If the language doesn't support getting syntax trees for a document, then bail out immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Null<SyntaxTree>(); } // if we have a cached result task use it if (_syntaxTreeResultTask != null) { // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // check to see if we already have the tree before actually going async if (TryGetSyntaxTree(out var tree)) { // stash a completed result task for this value for the next request (to reduce extraneous allocations of tasks) // don't use the actual async task because it depends on a specific cancellation token // its okay to cache the task and hold onto the SyntaxTree, because the DocumentState already keeps the SyntaxTree alive. Interlocked.CompareExchange(ref _syntaxTreeResultTask, Task.FromResult(tree), null); // _syntaxTreeResultTask is a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return _syntaxTreeResultTask!; } // do it async for real. // GetSyntaxTreeAsync returns a Task<SyntaxTree> so the ! operator here isn't suppressing a possible null ref, but rather allowing the // conversion from Task<SyntaxTree> to Task<SyntaxTree?> since Task itself isn't properly variant. return DocumentState.GetSyntaxTreeAsync(cancellationToken).AsTask()!; } internal SyntaxTree? GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } return DocumentState.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot([NotNullWhen(returnValue: true)] out SyntaxNode? root) { root = null; return this.TryGetSyntaxTree(out var tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <returns> /// The returned <see cref="SyntaxNode"/> will be <see langword="null"/> if <see /// cref="SupportsSyntaxTree"/> returns <see langword="false"/>. This function will return /// the same value if called multiple times. /// </returns> public async Task<SyntaxNode?> GetSyntaxRootAsync(CancellationToken cancellationToken = default) { if (!this.SupportsSyntaxTree) { return null; } var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode? GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken)!; return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel([NotNullWhen(returnValue: true)] out SemanticModel? semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> /// <returns> /// The returned <see cref="SemanticModel"/> may be <see langword="null"/> if <see /// cref="SupportsSemanticModel"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public async Task<SemanticModel?> GetSemanticModelAsync(CancellationToken cancellationToken = default) { try { if (!this.SupportsSemanticModel) { return null; } if (this.TryGetSemanticModel(out var semanticModel)) { return semanticModel; } var syntaxTree = await this.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = (await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false))!; var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // It looks like someone has set it. Try to reuse same semantic model, or assign the new model if that // fails. The lock is required since there is no compare-and-set primitive for WeakReference<T>. lock (original) { if (original.TryGetTarget(out semanticModel)) { return semanticModel; } original.SetTarget(result); return result; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) => this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) => this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) => this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified name. /// </summary> public Document WithName(string name) => this.Project.Solution.WithDocumentName(this.Id, name).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified folders. /// </summary> public Document WithFolders(IEnumerable<string> folders) => this.Project.Solution.WithDocumentFolders(this.Id, folders).GetDocument(this.Id)!; /// <summary> /// Creates a new instance of this document updated to have the specified file path. /// </summary> /// <param name="filePath"></param> // TODO (https://github.com/dotnet/roslyn/issues/37125): Solution.WithDocumentFilePath will throw if // filePath is null, but it's odd because we *do* support null file paths. Why can't you switch a // document back to null? public Document WithFilePath(string filePath) => this.Project.Solution.WithDocumentFilePath(this.Id, filePath).GetDocument(this.Id)!; /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes if (this.TryGetText(out var text) && oldDocument.TryGetText(out var oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { var textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = (await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false))!; var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); RoslynDebug.Assert(oldTree is object); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal virtual Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocument(this.Id, cancellationToken); return newSolution.GetDocument(this.Id)!; } else { return this; } } private string GetDebuggerDisplay() => this.Name; private AsyncLazy<DocumentOptionSet>? _cachedOptions; /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the document levels. /// </summary> /// <remarks> /// This method is async because this may require reading other files. In files that are already open, this is expected to be cheap and complete synchronously. /// </remarks> public Task<DocumentOptionSet> GetOptionsAsync(CancellationToken cancellationToken = default) => GetOptionsAsync(Project.Solution.Options, cancellationToken); [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", AllowCaptures = false)] internal Task<DocumentOptionSet> GetOptionsAsync(OptionSet solutionOptions, CancellationToken cancellationToken) { // TODO: we have this workaround since Solution.Options is not actually snapshot but just return Workspace.Options which violate snapshot model. // this doesn't validate whether same optionset is given to invalidate the cache or not. this is not new since existing implementation // also didn't check whether Workspace.Option is same as before or not. all weird-ness come from the root cause of Solution.Options violating // snapshot model. once that is fixed, we can remove this workaround - https://github.com/dotnet/roslyn/issues/19284 if (_cachedOptions == null) { InitializeCachedOptions(solutionOptions); } Contract.ThrowIfNull(_cachedOptions); return _cachedOptions.GetValueAsync(cancellationToken); } private void InitializeCachedOptions(OptionSet solutionOptions) { var newAsyncLazy = new AsyncLazy<DocumentOptionSet>(async c => { var optionsService = Project.Solution.Workspace.Services.GetRequiredService<IOptionService>(); var documentOptionSet = await optionsService.GetUpdatedOptionSetForDocumentAsync(this, solutionOptions, c).ConfigureAwait(false); return new DocumentOptionSet(documentOptionSet, Project.Language); }, cacheResult: true); Interlocked.CompareExchange(ref _cachedOptions, newAsyncLazy, comparand: null); } internal Task<ImmutableDictionary<string, string>> GetAnalyzerOptionsAsync(CancellationToken cancellationToken) { var projectFilePath = Project.FilePath; // We need to work out path to this document. Documents may not have a "real" file path if they're something created // as a part of a code action, but haven't been written to disk yet. string? effectiveFilePath = null; if (FilePath != null) { effectiveFilePath = FilePath; } else if (Name != null && projectFilePath != null) { var projectPath = PathUtilities.GetDirectoryName(projectFilePath); if (!RoslynString.IsNullOrEmpty(projectPath) && PathUtilities.GetDirectoryName(projectFilePath) is string directory) { effectiveFilePath = PathUtilities.CombinePathsUnchecked(directory, Name); } } if (effectiveFilePath != null) { return Project.State.GetAnalyzerOptionsForPathAsync(effectiveFilePath, cancellationToken); } else { // Really no idea where this is going, so bail // TODO: use AnalyzerConfigOptions.EmptyDictionary, since we don't have a public dictionary return Task.FromResult(ImmutableDictionary.Create<string, string>(AnalyzerConfigOptions.KeyComparer)); } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/Core/Portable/LinkedFileDiffMerging/LinkedFileMergeSessionResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal sealed class LinkedFileMergeSessionResult { public Solution MergedSolution { get; } private readonly Dictionary<DocumentId, IEnumerable<TextSpan>> _mergeConflictCommentSpans = new(); public Dictionary<DocumentId, IEnumerable<TextSpan>> MergeConflictCommentSpans => _mergeConflictCommentSpans; public LinkedFileMergeSessionResult(Solution mergedSolution, IEnumerable<LinkedFileMergeResult> fileMergeResults) { this.MergedSolution = mergedSolution; foreach (var fileMergeResult in fileMergeResults) { foreach (var documentId in fileMergeResult.DocumentIds) { _mergeConflictCommentSpans.Add(documentId, fileMergeResult.MergeConflictResolutionSpans); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal sealed class LinkedFileMergeSessionResult { public Solution MergedSolution { get; } private readonly Dictionary<DocumentId, IEnumerable<TextSpan>> _mergeConflictCommentSpans = new(); public Dictionary<DocumentId, IEnumerable<TextSpan>> MergeConflictCommentSpans => _mergeConflictCommentSpans; public LinkedFileMergeSessionResult(Solution mergedSolution, IEnumerable<LinkedFileMergeResult> fileMergeResults) { this.MergedSolution = mergedSolution; foreach (var fileMergeResult in fileMergeResults) { foreach (var documentId in fileMergeResult.DocumentIds) { _mergeConflictCommentSpans.Add(documentId, fileMergeResult.MergeConflictResolutionSpans); } } } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/CombineNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class CombineNode<TInput1, TInput2> : IIncrementalGeneratorNode<(TInput1, TInput2)> { private readonly IIncrementalGeneratorNode<TInput1> _input1; private readonly IIncrementalGeneratorNode<TInput2> _input2; private readonly IEqualityComparer<(TInput1, TInput2)>? _comparer; public CombineNode(IIncrementalGeneratorNode<TInput1> input1, IIncrementalGeneratorNode<TInput2> input2, IEqualityComparer<(TInput1, TInput2)>? comparer = null) { _input1 = input1; _input2 = input2; _comparer = comparer; } public NodeStateTable<(TInput1, TInput2)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)> previousTable, CancellationToken cancellationToken) { // get both input tables var input1Table = graphState.GetLatestStateTableForNode(_input1); var input2Table = graphState.GetLatestStateTableForNode(_input2); if (input1Table.IsCached && input2Table.IsCached) { return previousTable; } var builder = previousTable.ToBuilder(); // Semantics of a join: // // When input1[i] is cached: // - cached if input2 is also cached // - modified otherwise // State of input1[i] otherwise. // get the input2 item var isInput2Cached = input2Table.IsCached; TInput2 input2 = input2Table.Single(); // append the input2 item to each item in input1 foreach (var entry1 in input1Table) { var state = (entry1.state, isInput2Cached) switch { (EntryState.Cached, true) => EntryState.Cached, (EntryState.Cached, false) => EntryState.Modified, _ => entry1.state }; var entry = (entry1.item, input2); if (state != EntryState.Modified || _comparer is null || !builder.TryModifyEntry(entry, _comparer)) { builder.AddEntry(entry, state); } } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<(TInput1, TInput2)> WithComparer(IEqualityComparer<(TInput1, TInput2)> comparer) => new CombineNode<TInput1, TInput2>(_input1, _input2, comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) { // We have to call register on both branches of the join, as they may chain up to different input nodes _input1.RegisterOutput(output); _input2.RegisterOutput(output); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class CombineNode<TInput1, TInput2> : IIncrementalGeneratorNode<(TInput1, TInput2)> { private readonly IIncrementalGeneratorNode<TInput1> _input1; private readonly IIncrementalGeneratorNode<TInput2> _input2; private readonly IEqualityComparer<(TInput1, TInput2)>? _comparer; public CombineNode(IIncrementalGeneratorNode<TInput1> input1, IIncrementalGeneratorNode<TInput2> input2, IEqualityComparer<(TInput1, TInput2)>? comparer = null) { _input1 = input1; _input2 = input2; _comparer = comparer; } public NodeStateTable<(TInput1, TInput2)> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<(TInput1, TInput2)> previousTable, CancellationToken cancellationToken) { // get both input tables var input1Table = graphState.GetLatestStateTableForNode(_input1); var input2Table = graphState.GetLatestStateTableForNode(_input2); if (input1Table.IsCached && input2Table.IsCached) { return previousTable; } var builder = previousTable.ToBuilder(); // Semantics of a join: // // When input1[i] is cached: // - cached if input2 is also cached // - modified otherwise // State of input1[i] otherwise. // get the input2 item var isInput2Cached = input2Table.IsCached; TInput2 input2 = input2Table.Single(); // append the input2 item to each item in input1 foreach (var entry1 in input1Table) { var state = (entry1.state, isInput2Cached) switch { (EntryState.Cached, true) => EntryState.Cached, (EntryState.Cached, false) => EntryState.Modified, _ => entry1.state }; var entry = (entry1.item, input2); if (state != EntryState.Modified || _comparer is null || !builder.TryModifyEntry(entry, _comparer)) { builder.AddEntry(entry, state); } } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<(TInput1, TInput2)> WithComparer(IEqualityComparer<(TInput1, TInput2)> comparer) => new CombineNode<TInput1, TInput2>(_input1, _input2, comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) { // We have to call register on both branches of the join, as they may chain up to different input nodes _input1.RegisterOutput(output); _input2.RegisterOutput(output); } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SimpleNameSyntaxExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SimpleNameSyntaxExtensions { public static ExpressionSyntax GetLeftSideOfDot(this SimpleNameSyntax name) { Debug.Assert(name.IsSimpleMemberAccessExpressionName() || name.IsMemberBindingExpressionName() || name.IsRightSideOfQualifiedName() || name.IsParentKind(SyntaxKind.NameMemberCref)); if (name.IsSimpleMemberAccessExpressionName()) { return ((MemberAccessExpressionSyntax)name.Parent).Expression; } else if (name.IsMemberBindingExpressionName()) { return name.GetParentConditionalAccessExpression().Expression; } else if (name.IsRightSideOfQualifiedName()) { return ((QualifiedNameSyntax)name.Parent).Left; } else { return ((QualifiedCrefSyntax)name.Parent.Parent).Container; } } // Returns true if this looks like a possible type name that is on it's own (i.e. not after // a dot). This function is not exhaustive and additional checks may be added if they are // believed to be valuable. public static bool LooksLikeStandaloneTypeName(this SimpleNameSyntax simpleName) { if (simpleName == null) { return false; } // Isn't stand-alone if it's on the right of a dot/arrow if (simpleName.IsRightSideOfDotOrArrow()) { return false; } // type names can't be invoked. if (simpleName.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation) && invocation.Expression == simpleName) { return false; } // type names can't be indexed into. if (simpleName.IsParentKind(SyntaxKind.ElementAccessExpression, out ElementAccessExpressionSyntax elementAccess) && elementAccess.Expression == simpleName) { return false; } if (simpleName.Identifier.CouldBeKeyword()) { // Something that looks like a keyword is almost certainly not intended to be a // "Standalone type name". // // 1. Users are not going to name types the same name as C# keywords (contextual or otherwise). // 2. Types in .NET are virtually always start with a Uppercase. While keywords are lowercase) // // Having a lowercase identifier which matches a c# keyword is enough of a signal // to just not treat this as a standalone type name (even though for some identifiers // it could be according to the language). return false; } // Looks good. However, feel free to add additional checks if this function is too // lenient in some circumstances. return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SimpleNameSyntaxExtensions { public static ExpressionSyntax GetLeftSideOfDot(this SimpleNameSyntax name) { Debug.Assert(name.IsSimpleMemberAccessExpressionName() || name.IsMemberBindingExpressionName() || name.IsRightSideOfQualifiedName() || name.IsParentKind(SyntaxKind.NameMemberCref)); if (name.IsSimpleMemberAccessExpressionName()) { return ((MemberAccessExpressionSyntax)name.Parent).Expression; } else if (name.IsMemberBindingExpressionName()) { return name.GetParentConditionalAccessExpression().Expression; } else if (name.IsRightSideOfQualifiedName()) { return ((QualifiedNameSyntax)name.Parent).Left; } else { return ((QualifiedCrefSyntax)name.Parent.Parent).Container; } } // Returns true if this looks like a possible type name that is on it's own (i.e. not after // a dot). This function is not exhaustive and additional checks may be added if they are // believed to be valuable. public static bool LooksLikeStandaloneTypeName(this SimpleNameSyntax simpleName) { if (simpleName == null) { return false; } // Isn't stand-alone if it's on the right of a dot/arrow if (simpleName.IsRightSideOfDotOrArrow()) { return false; } // type names can't be invoked. if (simpleName.IsParentKind(SyntaxKind.InvocationExpression, out InvocationExpressionSyntax invocation) && invocation.Expression == simpleName) { return false; } // type names can't be indexed into. if (simpleName.IsParentKind(SyntaxKind.ElementAccessExpression, out ElementAccessExpressionSyntax elementAccess) && elementAccess.Expression == simpleName) { return false; } if (simpleName.Identifier.CouldBeKeyword()) { // Something that looks like a keyword is almost certainly not intended to be a // "Standalone type name". // // 1. Users are not going to name types the same name as C# keywords (contextual or otherwise). // 2. Types in .NET are virtually always start with a Uppercase. While keywords are lowercase) // // Having a lowercase identifier which matches a c# keyword is enough of a signal // to just not treat this as a standalone type name (even though for some identifiers // it could be according to the language). return false; } // Looks good. However, feel free to add additional checks if this function is too // lenient in some circumstances. return true; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/Core/Portable/ExtractInterface/AbstractExtractInterfaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var syntaxFactsService = refactoringResult.DocumentToExtractFrom.GetLanguageService<ISyntaxFactsService>(); var originalDocumentSyntaxRoot = await refactoringResult.DocumentToExtractFrom.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fileBanner = syntaxFactsService.GetFileBanner(originalDocumentSyntaxRoot); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, fileBanner, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractInterface { internal abstract class AbstractExtractInterfaceService : ILanguageService { protected abstract Task<SyntaxNode> GetTypeDeclarationAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken); protected abstract Task<Solution> UpdateMembersWithExplicitImplementationsAsync( Solution unformattedSolution, IReadOnlyList<DocumentId> documentId, INamedTypeSymbol extractedInterfaceSymbol, INamedTypeSymbol typeToExtractFrom, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken); internal abstract string GetContainingNamespaceDisplay(INamedTypeSymbol typeSymbol, CompilationOptions compilationOptions); internal abstract bool ShouldIncludeAccessibilityModifier(SyntaxNode typeNode); public async Task<ImmutableArray<ExtractInterfaceCodeAction>> GetExtractInterfaceCodeActionAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync(document, span.Start, TypeDiscoveryRule.TypeNameOnly, cancellationToken).ConfigureAwait(false); return typeAnalysisResult.CanExtractInterface ? ImmutableArray.Create(new ExtractInterfaceCodeAction(this, typeAnalysisResult)) : ImmutableArray<ExtractInterfaceCodeAction>.Empty; } public async Task<ExtractInterfaceResult> ExtractInterfaceAsync( Document documentWithTypeToExtractFrom, int position, Action<string, NotificationSeverity> errorHandler, CancellationToken cancellationToken) { var typeAnalysisResult = await AnalyzeTypeAtPositionAsync( documentWithTypeToExtractFrom, position, TypeDiscoveryRule.TypeDeclaration, cancellationToken).ConfigureAwait(false); if (!typeAnalysisResult.CanExtractInterface) { errorHandler(typeAnalysisResult.ErrorMessage, NotificationSeverity.Error); return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(typeAnalysisResult, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceTypeAnalysisResult> AnalyzeTypeAtPositionAsync( Document document, int position, TypeDiscoveryRule typeDiscoveryRule, CancellationToken cancellationToken) { var typeNode = await GetTypeDeclarationAsync(document, position, typeDiscoveryRule, cancellationToken).ConfigureAwait(false); if (typeNode == null) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var type = semanticModel.GetDeclaredSymbol(typeNode, cancellationToken); if (type == null || type.Kind != SymbolKind.NamedType) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_selection_is_not_inside_a_class_interface_struct; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } var typeToExtractFrom = type as INamedTypeSymbol; var extractableMembers = typeToExtractFrom.GetMembers().Where(IsExtractableMember); if (!extractableMembers.Any()) { var errorMessage = FeaturesResources.Could_not_extract_interface_colon_The_type_does_not_contain_any_member_that_can_be_extracted_to_an_interface; return new ExtractInterfaceTypeAnalysisResult(errorMessage); } return new ExtractInterfaceTypeAnalysisResult(document, typeNode, typeToExtractFrom, extractableMembers); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync(ExtractInterfaceTypeAnalysisResult refactoringResult, CancellationToken cancellationToken) { var containingNamespaceDisplay = refactoringResult.TypeToExtractFrom.ContainingNamespace.IsGlobalNamespace ? string.Empty : refactoringResult.TypeToExtractFrom.ContainingNamespace.ToDisplayString(); var extractInterfaceOptions = await GetExtractInterfaceOptionsAsync( refactoringResult.DocumentToExtractFrom, refactoringResult.TypeToExtractFrom, refactoringResult.ExtractableMembers, containingNamespaceDisplay, cancellationToken).ConfigureAwait(false); if (extractInterfaceOptions.IsCancelled) { return new ExtractInterfaceResult(succeeded: false); } return await ExtractInterfaceFromAnalyzedTypeAsync(refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); } public async Task<ExtractInterfaceResult> ExtractInterfaceFromAnalyzedTypeAsync( ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var solution = refactoringResult.DocumentToExtractFrom.Project.Solution; var extractedInterfaceSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility: ShouldIncludeAccessibilityModifier(refactoringResult.TypeNode) ? refactoringResult.TypeToExtractFrom.DeclaredAccessibility : Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), typeKind: TypeKind.Interface, name: extractInterfaceOptions.InterfaceName, typeParameters: ExtractTypeHelpers.GetRequiredTypeParametersForMembers(refactoringResult.TypeToExtractFrom, extractInterfaceOptions.IncludedMembers), members: CreateInterfaceMembers(extractInterfaceOptions.IncludedMembers)); switch (extractInterfaceOptions.Location) { case ExtractInterfaceOptionsResult.ExtractLocation.NewFile: var containingNamespaceDisplay = GetContainingNamespaceDisplay(refactoringResult.TypeToExtractFrom, refactoringResult.DocumentToExtractFrom.Project.CompilationOptions); return await ExtractInterfaceToNewFileAsync( solution, containingNamespaceDisplay, extractedInterfaceSymbol, refactoringResult, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); case ExtractInterfaceOptionsResult.ExtractLocation.SameFile: return await ExtractInterfaceToSameFileAsync( solution, refactoringResult, extractedInterfaceSymbol, extractInterfaceOptions, cancellationToken).ConfigureAwait(false); default: throw new InvalidOperationException($"Unable to extract interface for operation of type {extractInterfaceOptions.GetType()}"); } } private async Task<ExtractInterfaceResult> ExtractInterfaceToNewFileAsync( Solution solution, string containingNamespaceDisplay, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceTypeAnalysisResult refactoringResult, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var syntaxFactsService = refactoringResult.DocumentToExtractFrom.GetLanguageService<ISyntaxFactsService>(); var originalDocumentSyntaxRoot = await refactoringResult.DocumentToExtractFrom.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fileBanner = syntaxFactsService.GetFileBanner(originalDocumentSyntaxRoot); var (unformattedInterfaceDocument, _) = await ExtractTypeHelpers.AddTypeToNewFileAsync( symbolMapping.AnnotatedSolution, containingNamespaceDisplay, extractInterfaceOptions.FileName, refactoringResult.DocumentToExtractFrom.Project.Id, refactoringResult.DocumentToExtractFrom.Folders, extractedInterfaceSymbol, fileBanner, cancellationToken).ConfigureAwait(false); var completedUnformattedSolution = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedInterfaceDocument.Project.Solution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( completedUnformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(unformattedInterfaceDocument.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: unformattedInterfaceDocument.Id); } private async Task<ExtractInterfaceResult> ExtractInterfaceToSameFileAsync( Solution solution, ExtractInterfaceTypeAnalysisResult refactoringResult, INamedTypeSymbol extractedInterfaceSymbol, ExtractInterfaceOptionsResult extractInterfaceOptions, CancellationToken cancellationToken) { // Track all of the symbols we need to modify, which includes the original type declaration being modified var symbolMapping = await AnnotatedSymbolMapping.CreateAsync( extractInterfaceOptions.IncludedMembers, solution, refactoringResult.TypeNode, cancellationToken).ConfigureAwait(false); var document = symbolMapping.AnnotatedSolution.GetDocument(refactoringResult.DocumentToExtractFrom.Id); var (documentWithInterface, _) = await ExtractTypeHelpers.AddTypeToExistingFileAsync( document, extractedInterfaceSymbol, symbolMapping, cancellationToken).ConfigureAwait(false); var unformattedSolution = documentWithInterface.Project.Solution; // After the interface is inserted, update the original type to show it implements the new interface var unformattedSolutionWithUpdatedType = await GetSolutionWithOriginalTypeUpdatedAsync( unformattedSolution, symbolMapping.DocumentIdsToSymbolMap.Keys.ToImmutableArray(), symbolMapping.TypeNodeAnnotation, refactoringResult.TypeToExtractFrom, extractedInterfaceSymbol, extractInterfaceOptions.IncludedMembers, symbolMapping.SymbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); var completedSolution = await GetFormattedSolutionAsync( unformattedSolutionWithUpdatedType, symbolMapping.DocumentIdsToSymbolMap.Keys.Concat(refactoringResult.DocumentToExtractFrom.Id), cancellationToken).ConfigureAwait(false); return new ExtractInterfaceResult( succeeded: true, updatedSolution: completedSolution, navigationDocumentId: refactoringResult.DocumentToExtractFrom.Id); } internal static Task<ExtractInterfaceOptionsResult> GetExtractInterfaceOptionsAsync( Document document, INamedTypeSymbol type, IEnumerable<ISymbol> extractableMembers, string containingNamespace, CancellationToken cancellationToken) { var conflictingTypeNames = type.ContainingNamespace.GetAllTypes(cancellationToken).Select(t => t.Name); var candidateInterfaceName = type.TypeKind == TypeKind.Interface ? type.Name : "I" + type.Name; var defaultInterfaceName = NameGenerator.GenerateUniqueName(candidateInterfaceName, name => !conflictingTypeNames.Contains(name)); var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); var notificationService = document.Project.Solution.Workspace.Services.GetService<INotificationService>(); var generatedNameTypeParameterSuffix = ExtractTypeHelpers.GetTypeParameterSuffix(document, type, extractableMembers); var service = document.Project.Solution.Workspace.Services.GetService<IExtractInterfaceOptionsService>(); return service.GetExtractInterfaceOptionsAsync( syntaxFactsService, notificationService, extractableMembers.ToList(), defaultInterfaceName, conflictingTypeNames.ToList(), containingNamespace, generatedNameTypeParameterSuffix, document.Project.Language); } private static async Task<Solution> GetFormattedSolutionAsync(Solution unformattedSolution, IEnumerable<DocumentId> documentIds, CancellationToken cancellationToken) { // Since code action performs formatting and simplification on a single document, // this ensures that anything marked with formatter or simplifier annotations gets // correctly handled as long as it it's in the listed documents var formattedSolution = unformattedSolution; foreach (var documentId in documentIds) { var document = formattedSolution.GetDocument(documentId); var formattedDocument = await Formatter.FormatAsync( document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); var simplifiedDocument = await Simplifier.ReduceAsync( formattedDocument, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false); formattedSolution = simplifiedDocument.Project.Solution; } return formattedSolution; } private async Task<Solution> GetSolutionWithOriginalTypeUpdatedAsync( Solution solution, ImmutableArray<DocumentId> documentIds, SyntaxAnnotation typeNodeAnnotation, INamedTypeSymbol typeToExtractFrom, INamedTypeSymbol extractedInterfaceSymbol, IEnumerable<ISymbol> includedMembers, ImmutableDictionary<ISymbol, SyntaxAnnotation> symbolToDeclarationAnnotationMap, CancellationToken cancellationToken) { // If an interface "INewInterface" is extracted from an interface "IExistingInterface", // then "INewInterface" is not marked as implementing "IExistingInterface" and its // extracted members are also not updated. if (typeToExtractFrom.TypeKind == TypeKind.Interface) { return solution; } var unformattedSolution = solution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(currentRoot, solution.Workspace); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var typeReference = syntaxGenerator.TypeExpression(extractedInterfaceSymbol); var typeDeclaration = currentRoot.GetAnnotatedNodes(typeNodeAnnotation).SingleOrDefault(); if (typeDeclaration == null) { continue; } var unformattedTypeDeclaration = syntaxGenerator.AddInterfaceType(typeDeclaration, typeReference).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(typeDeclaration, unformattedTypeDeclaration); unformattedSolution = document.WithSyntaxRoot(editor.GetChangedRoot()).Project.Solution; // Only update the first instance of the typedeclaration, // since it's not needed in all declarations break; } var updatedUnformattedSolution = await UpdateMembersWithExplicitImplementationsAsync( unformattedSolution, documentIds, extractedInterfaceSymbol, typeToExtractFrom, includedMembers, symbolToDeclarationAnnotationMap, cancellationToken).ConfigureAwait(false); return updatedUnformattedSolution; } private static ImmutableArray<ISymbol> CreateInterfaceMembers(IEnumerable<ISymbol> includedMembers) { using var _ = ArrayBuilder<ISymbol>.GetInstance(out var interfaceMembers); foreach (var member in includedMembers) { switch (member.Kind) { case SymbolKind.Event: var @event = member as IEventSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateEventSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true), type: @event.Type, explicitInterfaceImplementations: default, name: @event.Name)); break; case SymbolKind.Method: var method = member as IMethodSymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: method.RequiresUnsafeModifier()), returnType: method.ReturnType, refKind: method.RefKind, explicitInterfaceImplementations: default, name: method.Name, typeParameters: method.TypeParameters, parameters: method.Parameters, isInitOnly: method.IsInitOnly)); break; case SymbolKind.Property: var property = member as IPropertySymbol; interfaceMembers.Add(CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isAbstract: true, isUnsafe: property.RequiresUnsafeModifier()), type: property.Type, refKind: property.RefKind, explicitInterfaceImplementations: default, name: property.Name, parameters: property.Parameters, getMethod: property.GetMethod == null ? null : (property.GetMethod.DeclaredAccessibility == Accessibility.Public ? property.GetMethod : null), setMethod: property.SetMethod == null ? null : (property.SetMethod.DeclaredAccessibility == Accessibility.Public ? property.SetMethod : null), isIndexer: property.IsIndexer)); break; default: Debug.Assert(false, string.Format(FeaturesResources.Unexpected_interface_member_kind_colon_0, member.Kind.ToString())); break; } } return interfaceMembers.ToImmutable(); } internal virtual bool IsExtractableMember(ISymbol m) { if (m.IsStatic || m.DeclaredAccessibility != Accessibility.Public || m.Name == "<Clone>$") // TODO: Use WellKnownMemberNames.CloneMethodName when it's public. { return false; } if (m.Kind == SymbolKind.Event || m.IsOrdinaryMethod()) { return true; } if (m.Kind == SymbolKind.Property) { var prop = m as IPropertySymbol; return !prop.IsWithEvents && ((prop.GetMethod != null && prop.GetMethod.DeclaredAccessibility == Accessibility.Public) || (prop.SetMethod != null && prop.SetMethod.DeclaredAccessibility == Accessibility.Public)); } return false; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/CodeStyle/CSharpCodeStyleOptions_Parsing.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeStyle { internal static partial class CSharpCodeStyleOptions { public static CodeStyleOption2<ExpressionBodyPreference> ParseExpressionBodyPreference( string optionString, CodeStyleOption2<ExpressionBodyPreference> @default) { // optionString must be similar to true:error or when_on_single_line:suggestion. if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification(optionString, @default.Notification, out var value, out var notification)) { if (bool.TryParse(value, out var boolValue)) { return boolValue ? new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, notification) : new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, notification); } if (value == "when_on_single_line") { return new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenOnSingleLine, notification); } } return @default; } private static string GetExpressionBodyPreferenceEditorConfigString(CodeStyleOption2<ExpressionBodyPreference> value, CodeStyleOption2<ExpressionBodyPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { ExpressionBodyPreference.Never => $"false{notificationString}", ExpressionBodyPreference.WhenPossible => $"true{notificationString}", ExpressionBodyPreference.WhenOnSingleLine => $"when_on_single_line{notificationString}", _ => throw new NotSupportedException(), }; } public static CodeStyleOption2<AddImportPlacement> ParseUsingDirectivesPlacement( string optionString, CodeStyleOption2<AddImportPlacement> @default) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, @default.Notification, out var value, out var notification)) { return value switch { "inside_namespace" => new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, notification), "outside_namespace" => new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, notification), _ => throw new NotSupportedException(), }; } return @default; } public static string GetUsingDirectivesPlacementEditorConfigString(CodeStyleOption2<AddImportPlacement> value, CodeStyleOption2<AddImportPlacement> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { AddImportPlacement.InsideNamespace => $"inside_namespace{notificationString}", AddImportPlacement.OutsideNamespace => $"outside_namespace{notificationString}", _ => throw new NotSupportedException(), }; } public static CodeStyleOption2<NamespaceDeclarationPreference> ParseNamespaceDeclaration( string optionString, CodeStyleOption2<NamespaceDeclarationPreference> @default) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, @default.Notification, out var value, out var notification)) { return value switch { "block_scoped" => new(NamespaceDeclarationPreference.BlockScoped, notification), "file_scoped" => new(NamespaceDeclarationPreference.FileScoped, notification), _ => throw new NotSupportedException(), }; } return @default; } public static string GetNamespaceDeclarationEditorConfigString(CodeStyleOption2<NamespaceDeclarationPreference> value, CodeStyleOption2<NamespaceDeclarationPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { NamespaceDeclarationPreference.BlockScoped => $"block_scoped{notificationString}", NamespaceDeclarationPreference.FileScoped => $"file_scoped{notificationString}", _ => throw new NotSupportedException(), }; } private static CodeStyleOption2<PreferBracesPreference> ParsePreferBracesPreference( string optionString, CodeStyleOption2<PreferBracesPreference> defaultValue) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, defaultValue.Notification, out var value, out var notificationOption)) { if (bool.TryParse(value, out var boolValue)) { return boolValue ? new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.Always, notificationOption) : new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.None, notificationOption); } if (value == "when_multiline") { return new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.WhenMultiline, notificationOption); } } return defaultValue; } private static string GetPreferBracesPreferenceEditorConfigString(CodeStyleOption2<PreferBracesPreference> value, CodeStyleOption2<PreferBracesPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { PreferBracesPreference.None => $"false{notificationString}", PreferBracesPreference.WhenMultiline => $"when_multiline{notificationString}", PreferBracesPreference.Always => $"true{notificationString}", _ => throw ExceptionUtilities.Unreachable, }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeStyle { internal static partial class CSharpCodeStyleOptions { public static CodeStyleOption2<ExpressionBodyPreference> ParseExpressionBodyPreference( string optionString, CodeStyleOption2<ExpressionBodyPreference> @default) { // optionString must be similar to true:error or when_on_single_line:suggestion. if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification(optionString, @default.Notification, out var value, out var notification)) { if (bool.TryParse(value, out var boolValue)) { return boolValue ? new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, notification) : new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, notification); } if (value == "when_on_single_line") { return new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenOnSingleLine, notification); } } return @default; } private static string GetExpressionBodyPreferenceEditorConfigString(CodeStyleOption2<ExpressionBodyPreference> value, CodeStyleOption2<ExpressionBodyPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { ExpressionBodyPreference.Never => $"false{notificationString}", ExpressionBodyPreference.WhenPossible => $"true{notificationString}", ExpressionBodyPreference.WhenOnSingleLine => $"when_on_single_line{notificationString}", _ => throw new NotSupportedException(), }; } public static CodeStyleOption2<AddImportPlacement> ParseUsingDirectivesPlacement( string optionString, CodeStyleOption2<AddImportPlacement> @default) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, @default.Notification, out var value, out var notification)) { return value switch { "inside_namespace" => new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.InsideNamespace, notification), "outside_namespace" => new CodeStyleOption2<AddImportPlacement>(AddImportPlacement.OutsideNamespace, notification), _ => throw new NotSupportedException(), }; } return @default; } public static string GetUsingDirectivesPlacementEditorConfigString(CodeStyleOption2<AddImportPlacement> value, CodeStyleOption2<AddImportPlacement> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { AddImportPlacement.InsideNamespace => $"inside_namespace{notificationString}", AddImportPlacement.OutsideNamespace => $"outside_namespace{notificationString}", _ => throw new NotSupportedException(), }; } public static CodeStyleOption2<NamespaceDeclarationPreference> ParseNamespaceDeclaration( string optionString, CodeStyleOption2<NamespaceDeclarationPreference> @default) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, @default.Notification, out var value, out var notification)) { return value switch { "block_scoped" => new(NamespaceDeclarationPreference.BlockScoped, notification), "file_scoped" => new(NamespaceDeclarationPreference.FileScoped, notification), _ => throw new NotSupportedException(), }; } return @default; } public static string GetNamespaceDeclarationEditorConfigString(CodeStyleOption2<NamespaceDeclarationPreference> value, CodeStyleOption2<NamespaceDeclarationPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { NamespaceDeclarationPreference.BlockScoped => $"block_scoped{notificationString}", NamespaceDeclarationPreference.FileScoped => $"file_scoped{notificationString}", _ => throw new NotSupportedException(), }; } private static CodeStyleOption2<PreferBracesPreference> ParsePreferBracesPreference( string optionString, CodeStyleOption2<PreferBracesPreference> defaultValue) { if (CodeStyleHelpers.TryGetCodeStyleValueAndOptionalNotification( optionString, defaultValue.Notification, out var value, out var notificationOption)) { if (bool.TryParse(value, out var boolValue)) { return boolValue ? new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.Always, notificationOption) : new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.None, notificationOption); } if (value == "when_multiline") { return new CodeStyleOption2<PreferBracesPreference>(PreferBracesPreference.WhenMultiline, notificationOption); } } return defaultValue; } private static string GetPreferBracesPreferenceEditorConfigString(CodeStyleOption2<PreferBracesPreference> value, CodeStyleOption2<PreferBracesPreference> defaultValue) { var notificationString = CodeStyleHelpers.GetEditorConfigStringNotificationPart(value, defaultValue); return value.Value switch { PreferBracesPreference.None => $"false{notificationString}", PreferBracesPreference.WhenMultiline => $"when_multiline{notificationString}", PreferBracesPreference.Always => $"true{notificationString}", _ => throw ExceptionUtilities.Unreachable, }; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/EditorFeatures/Core.Wpf/EditAndContinue/EditAndContinueErrorTypeFormatDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(EditAndContinueErrorTypeDefinition.Name)] [UserVisible(true)] internal sealed class EditAndContinueErrorTypeFormatDefinition : EditorFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueErrorTypeFormatDefinition() { this.ForegroundBrush = Brushes.Purple; this.BackgroundCustomizable = false; this.DisplayName = EditorFeaturesResources.Rude_Edit; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue { [Export(typeof(EditorFormatDefinition))] [Name(EditAndContinueErrorTypeDefinition.Name)] [UserVisible(true)] internal sealed class EditAndContinueErrorTypeFormatDefinition : EditorFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public EditAndContinueErrorTypeFormatDefinition() { this.ForegroundBrush = Brushes.Purple; this.BackgroundCustomizable = false; this.DisplayName = EditorFeaturesResources.Rude_Edit; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Compilers/Server/VBCSCompiler/CSharpCompilerServer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class CSharpCompilerServer : CSharpCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Globalization; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.CompilerServer { internal sealed class CSharpCompilerServer : CSharpCompiler { private readonly Func<string, MetadataReferenceProperties, PortableExecutableReference> _metadataProvider; internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : this(metadataProvider, Path.Combine(buildPaths.ClientDirectory, ResponseFileName), args, buildPaths, libDirectory, analyzerLoader) { } internal CSharpCompilerServer(Func<string, MetadataReferenceProperties, PortableExecutableReference> metadataProvider, string? responseFile, string[] args, BuildPaths buildPaths, string? libDirectory, IAnalyzerAssemblyLoader analyzerLoader) : base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, libDirectory, analyzerLoader) { _metadataProvider = metadataProvider; } internal override Func<string, MetadataReferenceProperties, PortableExecutableReference> GetMetadataProvider() { return _metadataProvider; } } }
-1
dotnet/roslyn
55,294
Report telemetry for HotReload sessions
Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
tmat
2021-07-30T20:02:25Z
2021-08-04T15:47:54Z
ab1130af679d8908e85735d43b26f8e4f10198e5
3c4a83cbce9c9ff812b2d5c39f61fea03ebcd239
Report telemetry for HotReload sessions. Fixes https://github.com/dotnet/roslyn/issues/52128 Also add solution update logging.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EnumKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EnumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, }; public EnumKeywordRecommender() : base(SyntaxKind.EnumKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EnumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, }; public EnumKeywordRecommender() : base(SyntaxKind.EnumKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } } }
-1