repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/InvalidDynamicAttributeArgs.dll
MZ@ !L!This program cannot be run in DOS mode. $PELP!  $ @@ `@x$S@  H.text  `.reloc @@B$Hh ( * * * ** **BSJB v4.0.30319l#~p#Stringsp#USx#GUID#BlobW %3 9 `@q~@$'EYP X b[ b^ ja nc bf s !$)ADIa/d:M/|  <Module>SystemObject.ctorSystem.Collections.GenericList`1System.Runtime.CompilerServicesDynamicAttributeDictionary`2IsConstInvalidDynamicAttributeArgs.dllmscorlibSystem.CoreCF1F2F3F4F5F6M1M2get_P1set_P1valueget_P2set_P2P1P2 C\0 7BSȑ  z\V4            (( $$ $_CorDllMainmscoree.dll% @ 4
MZ@ !L!This program cannot be run in DOS mode. $PELP!  $ @@ `@x$S@  H.text  `.reloc @@B$Hh ( * * * ** **BSJB v4.0.30319l#~p#Stringsp#USx#GUID#BlobW %3 9 `@q~@$'EYP X b[ b^ ja nc bf s !$)ADIa/d:M/|  <Module>SystemObject.ctorSystem.Collections.GenericList`1System.Runtime.CompilerServicesDynamicAttributeDictionary`2IsConstInvalidDynamicAttributeArgs.dllmscorlibSystem.CoreCF1F2F3F4F5F6M1M2get_P1set_P1valueget_P2set_P2P1P2 C\0 7BSȑ  z\V4            (( $$ $_CorDllMainmscoree.dll% @ 4
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Emit/Attributes/AttributeTests_ObsoleteAttribute.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_ObsoleteAttribute Inherits BasicTestBase <Fact()> Public Sub TestObsoleteAttributeOnTypes() Dim source = <compilation> <file name="test.vb"><![CDATA[ Imports System Module Module1 Dim field1 As Class1 Property Prop1 As Class1 Sub Method1(c As Class1) End Sub Sub Main() Dim c As Class1 = Nothing field1 = c Prop1 = c Method1(New Class1()) Dim x As Mydeleg = Function(i) i End Sub End Module <Obsolete("Do not use this type", True)> Class Class1 End Class <Obsolete("Do not use A1", False)> <A2> Class A1 Inherits Attribute End Class <Obsolete> <A1> Class A2 Inherits Attribute End Class <A1> Class A3 Inherits Attribute End Class Class AttrWithType Inherits Attribute Sub New(t As Type) End Sub End Class <Obsolete> <Another> Class G(Of T, U) End Class <Obsolete> <AttrWithType(GetType(G(Of Integer, AnotherAttribute)))> Class AnotherAttribute Inherits Attribute End Class <AttrWithType(GetType(G(Of Integer, AnotherAttribute)))> Class AnotherAttribute1 Inherits Attribute End Class <System.Obsolete("This message" & " should be concat'ed", Not (False))> <SelfRecursive1> Class SelfRecursive1Attribute Inherits Attribute End Class <Obsolete> Public Delegate Function Mydeleg(x As Integer) As Integer <GooAttribute.BarAttribute.Baz> <Obsolete("Blah")> Class GooAttribute Inherits Attribute Class BazAttribute Inherits Attribute End Class Class BarAttribute Inherits GooAttribute End Class End Class Interface IGoo(Of T) End Interface <Obsolete> Class SelfReferenceInBase Implements IGoo(Of SelfReferenceInBase) End Class Class SelfReferenceInBase1 Implements IGoo(Of SelfReferenceInBase) End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "AnotherAttribute").WithArguments("AnotherAttribute"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "A1").WithArguments("A1", "Do not use A1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "G(Of Integer, AnotherAttribute)").WithArguments("G(Of Integer, AnotherAttribute)"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "SelfReferenceInBase").WithArguments("SelfReferenceInBase"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "Mydeleg").WithArguments("Mydeleg")) End Sub <Fact()> Public Sub TestObsoleteAttributeOnMembers() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Public Class Test Public Shared Sub Main() ObsoleteMethod1() ObsoleteMethod2() ObsoleteMethod3() ObsoleteMethod5() Dim t As Test = New Test() t.ObsoleteMethod4() Dim f = t.field1 Dim p1 = t.Property1 Dim p2 = t.Property2 AddHandler t.event1, Sub() Return t.ObsoleteExtensionMethod1() Dim func As Action(Of Integer) = AddressOf t.ObsoleteMethod4 func(1) Dim func1 As Action = AddressOf t.ObsoleteMethod4 func1() Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} Dim i1 = t1(10) Dim gt As GenericTest(Of Integer) = New GenericTest(Of Integer)() gt.ObsoleteMethod1(Of Double)() Dim gf = gt.field1 Dim gp1 = gt.Property1 AddHandler gt.event1, Sub(i) Return End Sub <Obsolete> Public Shared Sub ObsoleteMethod1() End Sub <Obsolete("Do not call this method")> Public Shared Sub ObsoleteMethod2() End Sub <Obsolete("Do not call this method", True)> Public Shared Sub ObsoleteMethod3() End Sub <Obsolete("Do not call this method")> Public Sub ObsoleteMethod4() End Sub <Obsolete("Do not call this method")> Public Sub ObsoleteMethod4(x As Integer) End Sub <Obsolete(Nothing, True)> Public Shared Sub ObsoleteMethod5() End Sub <Obsolete> Public Sub New() End Sub <Obsolete("Do not use this field")> Public field1 As Integer = 0 <Obsolete("Do not use this property")> Public Property Property1 As Integer <Obsolete("Do not use this property")> Public Property Property2 As Integer Get Return 11 End Get Set(value As Integer) End Set End Property <Obsolete("Do not use this event")> Public Event event1 As Action Public ReadOnly Property Prop2 As Integer <Obsolete> Get Return 10 End Get End Property Public Property Prop3 As Integer Get Return 10 End Get <Obsolete> Set(value As Integer) End Set End Property Public Custom Event event2 As Action <Obsolete> AddHandler(value As Action) End AddHandler <Obsolete> RemoveHandler(value As Action) End RemoveHandler <Obsolete> RaiseEvent() End RaiseEvent End Event <Obsolete> Default Public ReadOnly Property Item(x As Integer) Get Return 10 End Get End Property End Class Public Class GenericTest(Of T) <Obsolete> Public Sub ObsoleteMethod1(Of U)() End Sub <Obsolete("Do not use this field")> Public field1 As T = Nothing <Obsolete("Do not use this property")> Public Property Property1 As T <Obsolete("Do not use this event")> Public Event event1 As Action(Of T) End Class Public Module TestExtension <Obsolete("Do not call this extension method")> <Extension> Public Sub ObsoleteExtensionMethod1(t As Test) End Sub End Module ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {TestMetadata.Net40.SystemCore}).AssertTheseDiagnostics( <![CDATA[ BC40008: 'Public Shared Sub ObsoleteMethod1()' is obsolete. ObsoleteMethod1() ~~~~~~~~~~~~~~~~~ BC40000: 'Public Shared Sub ObsoleteMethod2()' is obsolete: 'Do not call this method'. ObsoleteMethod2() ~~~~~~~~~~~~~~~~~ BC30668: 'Public Shared Sub ObsoleteMethod3()' is obsolete: 'Do not call this method'. ObsoleteMethod3() ~~~~~~~~~~~~~~~~~ BC31075: 'Public Shared Sub ObsoleteMethod5()' is obsolete. ObsoleteMethod5() ~~~~~~~~~~~~~~~~~ BC40008: 'Public Sub New()' is obsolete. Dim t As Test = New Test() ~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4()' is obsolete: 'Do not call this method'. t.ObsoleteMethod4() ~~~~~~~~~~~~~~~~~~~ BC40000: 'Public field1 As Integer' is obsolete: 'Do not use this field'. Dim f = t.field1 ~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim p1 = t.Property1 ~~~~~~~~~~~ BC40000: 'Public Property Property2 As Integer' is obsolete: 'Do not use this property'. Dim p2 = t.Property2 ~~~~~~~~~~~ BC40000: 'Public Event event1 As Action' is obsolete: 'Do not use this event'. AddHandler t.event1, Sub() Return ~~~~~~~~ BC40000: 'Public Sub ObsoleteExtensionMethod1()' is obsolete: 'Do not call this extension method'. t.ObsoleteExtensionMethod1() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4(x As Integer)' is obsolete: 'Do not call this method'. Dim func As Action(Of Integer) = AddressOf t.ObsoleteMethod4 ~~~~~~~~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4()' is obsolete: 'Do not call this method'. Dim func1 As Action = AddressOf t.ObsoleteMethod4 ~~~~~~~~~~~~~~~~~ BC40008: 'Public Sub New()' is obsolete. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~ BC40000: 'Public Property Property2 As Integer' is obsolete: 'Do not use this property'. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~ BC40008: 'Public ReadOnly Default Property Item(x As Integer) As Object' is obsolete. Dim i1 = t1(10) ~~~~~~ BC40008: 'Public Sub ObsoleteMethod1(Of Double)()' is obsolete. gt.ObsoleteMethod1(Of Double)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public field1 As Integer' is obsolete: 'Do not use this field'. Dim gf = gt.field1 ~~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim gp1 = gt.Property1 ~~~~~~~~~~~~ BC40000: 'Public Event event1 As Action(Of Integer)' is obsolete: 'Do not use this event'. AddHandler gt.event1, Sub(i) Return ~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub TestObsoleteAttributeOnOperators() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Test Public Shared Sub Main() Dim t As New Test() t = 10 t = CType("10", Test) Dim c As New Test() Dim c1 As Test = -c Dim b1 As Boolean = If(c, True, False) If (c AndAlso c1) Then c1 += c End If End Sub <Obsolete> Public Shared Widening Operator CType(x As Integer) As Test Return New Test() End Operator <Obsolete> Public Shared Narrowing Operator CType(x As String) As Test Return New Test() End Operator <Obsolete> Public Shared Operator -(x As test) As Test Return New Test() End Operator <Obsolete> Public Shared Operator IsTrue(x As Test) As Boolean Return True End Operator <Obsolete> Public Shared Operator IsFalse(x As test) As Boolean Return False End Operator <Obsolete> Public Shared Operator +(x As Test, y As Test) As Test Return New Test() End Operator <Obsolete> Public Shared Operator And(x As Test, y As Test) As Test Return New Test() End Operator End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "10").WithArguments("Public Shared Widening Operator CType(x As Integer) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "CType(""10"", Test)").WithArguments("Public Shared Narrowing Operator CType(x As String) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "-c").WithArguments("Public Shared Operator -(x As Test) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c").WithArguments("Public Shared Operator IsTrue(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c AndAlso c1").WithArguments("Public Shared Operator And(x As Test, y As Test) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c AndAlso c1").WithArguments("Public Shared Operator IsFalse(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "(c AndAlso c1)").WithArguments("Public Shared Operator IsTrue(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c1 += c").WithArguments("Public Shared Operator +(x As Test, y As Test) As Test")) End Sub <Fact> Public Sub TestObsoleteAttributeInMetadata() Dim peSource = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class TestClass1 End Class <Obsolete("TestClass2 is obsolete")> Public Class TestClass2 End Class <Obsolete("Do not use TestClass3", True)> Public Class TestClass3 End Class <Obsolete("TestClass4 is obsolete", False)> Public Class TestClass4 End Class <Obsolete(Nothing, True)> Public Module TestModule Public Sub TestMethod() End Sub End Module Public Class TestClass <Obsolete("Do not use TestMethod")> Public Sub TestMethod() End Sub <Obsolete("Do not use Prop1", False)> Public Property Prop1 As Integer <Obsolete("Do not use field1", True)> Public field1 As TestClass <Obsolete("Do not use event", True)> Public Event event1 As Action End Class ]]> </file> </compilation> Dim peReference = MetadataReference.CreateFromImage(CreateCompilationWithMscorlib40AndVBRuntime(peSource).EmitToArray()) Dim source = <compilation> <file name="b.vb"><![CDATA[ Public Class Test Public Shared Sub goo1(c As TestClass1) End Sub Public Shared Sub goo2(c As TestClass2) End Sub Public Shared Sub goo3(c As TestClass3) End Sub Public Shared Sub goo4(c As TestClass4) End Sub Public Shared Sub Main() Dim c As TestClass = New TestClass() c.TestMethod() Dim i = c.Prop1 c = c.field1 AddHandler c.event1, Sub() Return TestModule.TestMethod() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndReferences(source, {peReference}).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "TestClass1").WithArguments("TestClass1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "TestClass2").WithArguments("TestClass2", "TestClass2 is obsolete"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "TestClass3").WithArguments("TestClass3", "Do not use TestClass3"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "TestClass4").WithArguments("TestClass4", "TestClass4 is obsolete"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "c.TestMethod()").WithArguments("Public Sub TestMethod()", "Do not use TestMethod"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "c.Prop1").WithArguments("Public Property Prop1 As Integer", "Do not use Prop1"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "c.field1").WithArguments("Public field1 As TestClass", "Do not use field1"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "c.event1").WithArguments("Public Event event1 As System.Action", "Do not use event"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbolNoMessage1, "TestModule").WithArguments("TestModule")) End Sub <Fact> Public Sub TestObsoleteAttributeCycles() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Test <Obsolete("F1 is obsolete")> <SomeAttr(F1)> Public Const F1 As Integer = 10 <Obsolete("F2 is obsolete", True)> <SomeAttr(F3)> Public Const F2 As Integer = 10 <Obsolete("F3 is obsolete")> <SomeAttr(F2)> Public Const F3 As Integer = 10 <Obsolete(F4, True)> Public Const F4 As String = "blah" <Obsolete(F5)> Public F5 As String = "blah" <Obsolete(P1, True)> Public ReadOnly Property P1 As String Get Return "blah" End Get End Property <Obsolete> <SomeAttr(P2, True)> Public ReadOnly Property P2 As String Get Return "blah" End Get End Property <Obsolete(Method1)> Public Sub Method1() End Sub <Obsolete()> <SomeAttr1(Method2)> Public Sub Method2() End Sub <Obsolete(F6)> <SomeAttr(F6)> <SomeAttr(F7)> Public Const F6 As String = "F6 is obsolete" <Obsolete(F7, True)> <SomeAttr(F6)> <SomeAttr(F7)> Public Const F7 As String = "F7 is obsolete" End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=True)> Public Class SomeAttr Inherits Attribute Public Sub New(x As Integer) End Sub Public Sub New(x As String) End Sub End Class Public Class SomeAttr1 Inherits Attribute Public Sub New(x As Action) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "F5"), Diagnostic(ERRID.ERR_RequiredConstExpr, "F5"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "P1"), Diagnostic(ERRID.ERR_RequiredConstExpr, "P1"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "P2"), Diagnostic(ERRID.ERR_NoArgumentCountOverloadCandidates1, "SomeAttr").WithArguments("New"), Diagnostic(ERRID.ERR_RequiredConstExpr, "P2"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "Method1"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "Method2")) End Sub <Fact> Public Sub TestObsoleteAttributeSuppress() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType Public Shared Instance As SomeType Public Const Message As String = "goo" End Class <Obsolete> Module Mod1 Dim someField As SomeType = SomeType.Instance Public Property someProp As SomeType Sub goo(x As SomeType) End Sub End Module Public Class Test <Obsolete> Dim someField As SomeType = SomeType.Instance <Obsolete> Dim someFuncField As Func(Of SomeType) = Function() New SomeType() <Obsolete> Event someEvent As Action(Of SomeType) <Obsolete> Function goo(x As SomeType) As SomeType Dim y As SomeType = New SomeType() Return x End Function End Class <Obsolete> Public Class Base(Of T) End Class <Obsolete> Public Class Derived Inherits Base(Of Base(Of Integer)) End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAttributeSuppress_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType End Class <Obsolete> Public Delegate Sub MyDeleg() Public Class Test <Obsolete> Public Shared Property someProp As SomeType <Obsolete> Default Public Property Item(x As SomeType) As SomeType Get Return Nothing End Get <Obsolete> Set(value As SomeType) Dim y As SomeType = New SomeType() End Set End Property <Obsolete> Custom Event goo As MyDeleg AddHandler(value As MyDeleg) End AddHandler RemoveHandler(value As MyDeleg) End RemoveHandler RaiseEvent() End RaiseEvent End Event <Obsolete()> Public Property Prop1 As SomeType Get Return New SomeType() End Get Set(ByVal Value As SomeType) Dim p As New SomeType() End Set End Property End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAndPropertyAccessors() Dim source = <compilation> <file><![CDATA[ Imports System Namespace Windows.Foundation.Metadata Public NotInheritable Class DeprecatedAttribute Inherits Attribute Public Sub New(message As String, type As DeprecationType, version As UInteger) End Sub End Class Public Enum DeprecationType Deprecate Remove End Enum End Namespace ]]> </file> <file><![CDATA[ Imports Windows.Foundation.Metadata <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class A End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class B End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class C End Class Class D ReadOnly Property P As Object Get Return New A() End Get End Property <Deprecated(Nothing, DeprecationType.Deprecate, 0)>ReadOnly Property Q As Object Get Return New B() End Get End Property ReadOnly Property R As Object <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Get Return New C() End Get End Property End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC40008: 'A' is obsolete. Return New A() ~ ]]></errors>) End Sub <Fact> Public Sub TestObsoleteAndEventAccessors() Dim source = <compilation> <file><![CDATA[ Imports System Namespace Windows.Foundation.Metadata Public NotInheritable Class DeprecatedAttribute Inherits Attribute Public Sub New(message As String, type As DeprecationType, version As UInteger) End Sub End Class Public Enum DeprecationType Deprecate Remove End Enum End Namespace ]]> </file> <file><![CDATA[ Imports System Imports Windows.Foundation.Metadata <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class A End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class B End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class C End Class Class D Custom Event E As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) M(New A()) End RemoveHandler RaiseEvent End RaiseEvent End Event <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Custom Event F As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) M(New B()) End RemoveHandler RaiseEvent End RaiseEvent End Event Custom Event G As EventHandler AddHandler(value As EventHandler) End AddHandler <Deprecated(Nothing, DeprecationType.Deprecate, 0)>RemoveHandler(value As EventHandler) M(New C()) End RemoveHandler RaiseEvent End RaiseEvent End Event Shared Sub M(o As Object) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC40008: 'A' is obsolete. M(New A()) ~ BC31142: 'Windows.Foundation.Metadata.DeprecatedAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Deprecated(Nothing, DeprecationType.Deprecate, 0)>RemoveHandler(value As EventHandler) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub TestObsoleteAttributeCycles_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Goo> Class Goo Inherits Base End Class <Goo> class Base Inherits System.Attribute Public Class Nested Inherits Goo End Class End Class ]]> </file> </compilation> CompileAndVerify(source) source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType Public Shared Instance As SomeType Public Const Message As String = "goo" End Class Public Class SomeAttr Inherits Attribute Public Sub New(message As String) End Sub End Class <Obsolete(SomeType.Message)> Public Class Derived Inherits Base End Class Public Class Base <Obsolete(SomeType.Message)> Public Property SomeProp As SomeType End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithConcurrentBuild(False)).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAttributeP2PReference() Dim s = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> public Class C <Obsolete> public sub Goo() end sub end class ]]> </file> </compilation> Dim other = CreateCompilationWithMscorlib40(s) s = <compilation> <file name="b.vb"><![CDATA[ Public Class A Sub New(o As C) o.Goo() end sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndReferences(s, {New VisualBasicCompilationReference(other)}).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C").WithArguments("C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "o.Goo()").WithArguments("Public Sub Goo()")) End Sub <Fact> Public Sub TestObsoleteAttributeOnMembers2() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 Property p As String <Obsolete("", False)> Get Return "hello" End Get <Obsolete> Set(value As String) End Set End Property <Obsolete> WithEvents p1 As New C2 Sub handler() Handles p1.XEvent End Sub <Obsolete> Sub handler2() Handles p1.XEvent End Sub Custom Event goo As MyDeleg AddHandler(value As MyDeleg) End AddHandler RemoveHandler(value As MyDeleg) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class C2 <Obsolete> Public Event XEvent() Sub bar(s As String) End Sub Sub goo() Dim s As New C1 s.p += "as" bar(s.p) End Sub End Class <Obsolete> Public Delegate Sub MyDeleg() ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "XEvent").WithArguments("Public Event XEvent()"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p += ""as""").WithArguments("Set", "Public Property p As String"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p").WithArguments("Get", "Public Property p As String"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p").WithArguments("Get", "Public Property p As String")) End Sub <Fact> <WorkItem(546636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546636")> Public Sub TestObsoleteAttributeOnAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=True)> Public Class Att Inherits Attribute <Obsolete("Constructor", True)> Public Sub New() End Sub <Obsolete("Property", True)> Public Property Prop As Integer Get Return 1 End Get Set(value As Integer) End Set End Property <Obsolete("Field", True)> Public Field As Integer End Class <Att> <Att(Field:=1)> <Att(Prop:=1)> Public Class Test <Att()> Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att()").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Field:=1").WithArguments("Public Field As Integer", "Field"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att(Field:=1)").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Prop:=1").WithArguments("Public Property Prop As Integer", "Property"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att(Prop:=1)").WithArguments("Public Sub New()", "Constructor")) End Sub <Fact> Public Sub TestObsoleteAttributeOnMembers3() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace A.B <Obsolete> Public Class C <Obsolete> Public Shared Field1 As Integer = 10 <Obsolete> Public Class D <Obsolete> Public Shared Field2 As Integer = 20 End Class End Class <Obsolete> Public Class C1 Public Class D End Class End Class <Obsolete> Public Class C2(Of T) <Obsolete> Public Shared Field1 As Integer = 10 Public Class D End Class <Obsolete> Public Class E(Of U) End Class End Class End Namespace Class B(Of T) End Class Class D Inherits B(Of A.B.C1.D) End Class Class D1 Inherits B(Of A.B.C2(Of Integer).D) End Class Class D2 Inherits B(Of A.B.C2(Of Integer).E(Of Integer)) End Class Class Program Shared Sub Main() Dim x = A.B.C.Field1 Dim x1 = A.B.C.D.Field2 Dim y = New A.B.C1.D() Dim y1 = New A.B.C2(Of Integer).D() Dim y2 = A.B.C2(Of Integer).Field1 Dim y3 = New a.b.c2(Of Integer).E(Of Integer) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C1").WithArguments("A.B.C1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer).E(Of Integer)").WithArguments("A.B.C2(Of Integer).E(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C").WithArguments("A.B.C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.Field1").WithArguments("Public Shared Field1 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C").WithArguments("A.B.C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.D").WithArguments("A.B.C.D"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.D.Field2").WithArguments("Public Shared Field2 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C1").WithArguments("A.B.C1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of T)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer).Field1").WithArguments("Public Shared Field1 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "a.b.c2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "a.b.c2(Of Integer).E(Of Integer)").WithArguments("A.B.C2(Of Integer).E(Of Integer)")) End Sub Private ReadOnly ObsoleteAttributeSource As XElement = <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(message As String) End Sub Public Sub New(message As String, isError As Boolean) End Sub Public Property DiagnosticId As String Public Property UrlFormat As String End Class End Namespace ]]></file> <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="TEST1")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/BC40008", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_03() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}/{1}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_04() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/elementname-is-obsolete-visual-basic-warning")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/elementname-is-obsolete-visual-basic-warning", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadAttribute_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="TEST1")> Sub M1() End Sub Sub M2() M1() End Sub End Class Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(message As String) End Sub Public Sub New(message As String, isError As Boolean) End Sub Public Dim DiagnosticId As String Public Property DiagnosticId As String End Class End Namespace ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "DiagnosticId").WithArguments("DiagnosticId", "class", "System.ObsoleteAttribute").WithLocation(4, 15), Diagnostic(ERRID.ERR_MultiplyDefinedType3, "DiagnosticId").WithArguments("DiagnosticId", "Public DiagnosticId As String", "class").WithLocation(27, 25)) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_05() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1", UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("TEST1", diag.Id) Assert.Equal(ERRID.WRN_UseOfObsoleteSymbol2, DirectCast(diag.Code, ERRID)) Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadAttribute_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="A", DiagnosticId:="B", UrlFormat:="C", UrlFormat:="D")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("C", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_Suppression_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1")> Sub M1() End Sub <Obsolete> Sub M2() End Sub Sub M3() M1() M2() #Disable Warning TEST1 M1() M2() #Enable Warning TEST1 #Disable Warning BC40008 M1() M2() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.VerifyDiagnostics( Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(13, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(14, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(18, 9), Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(22, 9)) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_01() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1")> Public Sub M1() End Sub <Obsolete> Public Sub M2() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M3() M1() M2() #Disable Warning TEST1 M1() M2() #Enable Warning TEST1 #Disable Warning BC40008 M1() M2() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim expected = { Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(5, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(6, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(10, 9), Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(14, 9) } Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) comp2.VerifyDiagnostics(expected) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) comp2.VerifyDiagnostics(expected) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_02() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1")> Public Sub M1() End Sub <Obsolete("don't use", DiagnosticId:="TEST2")> Public Sub M2() End Sub <Obsolete("don't use", false, DiagnosticId:="TEST3")> Public Sub M3() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M4() M1() M2() M3() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim expected = { Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9), Diagnostic("TEST2", "M2()").WithArguments("Public Sub M2()", "don't use").WithLocation(6, 9), Diagnostic("TEST3", "M3()").WithArguments("Public Sub M3()", "don't use").WithLocation(7, 9) } Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) comp2.VerifyDiagnostics(expected) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) comp2.VerifyDiagnostics(expected) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_03() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1", UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Public Sub M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_04() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:=Nothing, UrlFormat:=Nothing)> Public Sub M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_01() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(Flag:=False, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property Flag As Boolean Public Property DiagnosticId As String End Class End Namespace ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_02() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1", UrlFormat:="TEST2")> Public Sub M1() End Sub End Class ]]></file> <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Dim DiagnosticId As String Public Dim UrlFormat As String End Class End Namespace ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_03() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property ByteProp As Byte Public Property SByteProp As SByte Public Property BooleanProp As Boolean Public Property ShortProp As Short Public Property UshortProp As UShort Public Property CharProp As Char Public Property IntProp As Integer Public Property UintProp As UInteger Public Property FloatProp As Single Public Property LongProp As Long Public Property UlongProp As ULong Public Property DoubleProp As Double Public Property EnumProp As E1 Public Property DiagnosticId As String End Class End Namespace Public Class C1 <Obsolete( ByteProp:=0, SByteProp:=0, BooleanProp:=false, ShortProp:=0, UShortProp:=0, CharProp:="\0", IntProp:=0, UIntProp:=0, FloatProp:=0, LongProp:=0, ULongProp:=0, DoubleProp:=0, EnumProp:=E1.A, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_04() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property IntProp As Integer() Public Property EnumProp As E1() Public Property DiagnosticId As String End Class End Namespace Public Class C1 <Obsolete( IntProp:={0, 1, 2}, EnumProp:={E1.A, E1.B}, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_05() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Char() Public Property UrlFormat As Char() End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:={"A"}, UrlFormat:={"B"})> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_06() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Char() Public Property UrlFormat As Char() End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:=Nothing, UrlFormat:=Nothing)> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_07() ' In this program C1.M1 has an ObsoleteAttribute with multiple values provided for DiagnosticId and UrlFormat Dim ilSource = " .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig instance void M1() cil managed { .custom instance void System.ObsoleteAttribute::.ctor() = ( 01 00 04 00 // .... 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 41 // T..DiagnosticId.A 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 42 // T..DiagnosticId.B 54 0E 09 55 72 6C 46 6F 72 6D 61 74 01 43 // T..UrlFormat.C 54 0E 09 55 72 6C 46 6F 72 6D 61 74 01 44 ) // T..UrlFormat.D // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C1::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit System.ObsoleteAttribute extends [mscorlib]System.Attribute { .field private string '<DiagnosticId>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field private string '<UrlFormat>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance string get_DiagnosticId() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_DiagnosticId .method public hidebysig specialname instance void set_DiagnosticId(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_DiagnosticId .method public hidebysig specialname instance string get_UrlFormat() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_UrlFormat .method public hidebysig specialname instance void set_UrlFormat(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_UrlFormat .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ObsoleteAttribute::.ctor .property instance string DiagnosticId() { .get instance string System.ObsoleteAttribute::get_DiagnosticId() .set instance void System.ObsoleteAttribute::set_DiagnosticId(string) } // end of property ObsoleteAttribute::DiagnosticId .property instance string UrlFormat() { .get instance string System.ObsoleteAttribute::get_UrlFormat() .set instance void System.ObsoleteAttribute::set_UrlFormat(string) } // end of property ObsoleteAttribute::UrlFormat } // end of class System.ObsoleteAttribute " Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim ilComp = CompileIL(ilSource) Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={ilComp}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Overloads Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("C", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_08() ' In this program C1.M1 has an ObsoleteAttribute with multiple values provided for DiagnosticId and UrlFormat Dim ilSource = " .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig instance void M1() cil managed { .custom instance void System.ObsoleteAttribute::.ctor() = ( 01 00 02 00 // .... 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 41 // T..DiagnosticId.A 0E 09 55 72 6C 46 6F 72 6D 61 74 01 42 ) // ..UrlFormat.B // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C1::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit System.ObsoleteAttribute extends [mscorlib]System.Attribute { .field private string '<DiagnosticId>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field private string '<UrlFormat>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance string get_DiagnosticId() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_DiagnosticId .method public hidebysig specialname instance void set_DiagnosticId(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_DiagnosticId .method public hidebysig specialname instance string get_UrlFormat() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_UrlFormat .method public hidebysig specialname instance void set_UrlFormat(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_UrlFormat .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ObsoleteAttribute::.ctor .property instance string DiagnosticId() { .get instance string System.ObsoleteAttribute::get_DiagnosticId() .set instance void System.ObsoleteAttribute::set_DiagnosticId(string) } // end of property ObsoleteAttribute::DiagnosticId .property instance string UrlFormat() { .get instance string System.ObsoleteAttribute::get_UrlFormat() .set instance void System.ObsoleteAttribute::set_UrlFormat(string) } // end of property ObsoleteAttribute::UrlFormat } // end of class System.ObsoleteAttribute " Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim ilComp = CompileIL(ilSource) Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={ilComp}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Overloads Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_09() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Object Public Property UrlFormat As Object End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:="A", UrlFormat:="B")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <WorkItem(578023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578023")> <Fact> Public Sub TestObsoleteInAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports X = C Imports Y = A(Of C) Imports Z = A(Of C()).B Imports C Imports A(Of C) Imports A(Of C()).B Class A(Of T) Friend Class B End Class End Class <System.Obsolete> Class C End Class Module M Private F As X Private G As Y Private H As Z End Module ]]> </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC40008: 'C' is obsolete. Imports X = C ~ BC40008: 'C' is obsolete. Imports Y = A(Of C) ~ BC40008: 'C' is obsolete. Imports Z = A(Of C()).B ~ BC40008: 'C' is obsolete. Imports C ~ BC40008: 'C' is obsolete. Imports A(Of C) ~ BC40008: 'C' is obsolete. Imports A(Of C()).B ~ </errors>) End Sub <WorkItem(580832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580832")> <Fact> Public Sub TestObsoleteOnVirtualMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A <Obsolete("A")> Public Overridable Sub M() End Sub End Class Public Class B Inherits A <Obsolete("B")> Public Overrides Sub M() End Sub Private Sub Base() MyBase.M() End Sub End Class Public Class C Inherits B <Obsolete("C")> Public Overrides Sub M() End Sub Private Sub Test(pa As A, pb As B, pc As C) pa.M() pb.M() pc.M() End Sub Private Sub Base() MyBase.M() End Sub End Class ]]> </file> </compilation>) ' Unlike in C#, VB does not walk up to the least-overridden method. compilation.AssertTheseDiagnostics(<errors> BC40000: 'Public Overridable Sub M()' is obsolete: 'A'. MyBase.M() ~~~~~~~~~~ BC40000: 'Public Overridable Sub M()' is obsolete: 'A'. pa.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'B'. pb.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'C'. pc.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'B'. MyBase.M() ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TestDeprecatedAttribute() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata <Deprecated("Class1 is deprecated.", DeprecationType.Deprecate, 0)> public class Class1 End Class <Deprecated("Class2 is deprecated.", DeprecationType.Deprecate, 0, Platform.Windows)> public class Class2 End Class <Deprecated("Class3 is deprecated.", DeprecationType.Remove, 1)> public class Class3 End Class <Deprecated("Class4 is deprecated.", DeprecationType.Remove, 0, Platform.WindowsPhone)> public class Class4 End Class ]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs) compilation1.VerifyDiagnostics() Dim source2 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata class Class5 Sub Test() Dim x1 As Class1 = Nothing Dim x2 As Class2 = Nothing Dim x3 As Class3 = Nothing Dim x4 As Class4 = Nothing Dim x5 As Object x5=x1 x5 = x2 x5 = x3 x5 = x4 End Sub End Class class Class6 Readonly Property P1 As Integer <Deprecated("P1.get is deprecated.", DeprecationType.Remove, 1)> get return 1 End Get End Property Custom Event E1 As System.Action <Deprecated("E1.add is deprecated.", DeprecationType.Remove, 1)> AddHandler(value As System.Action) End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim compilation2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat(New VisualBasicCompilationReference(compilation1))) Dim expected = <![CDATA[ BC40000: 'Class1' is obsolete: 'Class1 is deprecated.'. Dim x1 As Class1 = Nothing ~~~~~~ BC40000: 'Class2' is obsolete: 'Class2 is deprecated.'. Dim x2 As Class2 = Nothing ~~~~~~ BC30668: 'Class3' is obsolete: 'Class3 is deprecated.'. Dim x3 As Class3 = Nothing ~~~~~~ BC30668: 'Class4' is obsolete: 'Class4 is deprecated.'. Dim x4 As Class4 = Nothing ~~~~~~ BC31142: 'Windows.Foundation.Metadata.DeprecatedAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Deprecated("E1.add is deprecated.", DeprecationType.Remove, 1)> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> compilation2.AssertTheseDiagnostics(expected) compilation2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat(compilation1.EmitToImageReference())) compilation2.AssertTheseDiagnostics(expected) End Sub <Fact()> Public Sub TestDeprecatedAttribute001() Dim source1 = <![CDATA[ using System; using Windows.Foundation.Metadata; namespace Windows.Foundation.Metadata { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)] public sealed class DeprecatedAttribute : Attribute { public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version) { } public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version, Type contract) { } } public enum DeprecationType { Deprecate = 0, Remove = 1 } } public class Test { [Deprecated("hello", DeprecationType.Deprecate, 1, typeof(int))] public static void Goo() { } [Deprecated("hi", DeprecationType.Deprecate, 1)] public static void Bar() { } } ]]> Dim compilation1 = CreateCSharpCompilation("Dll1", source1.Value) Dim ref = compilation1.EmitToImageReference() Dim source2 = <compilation> <file name="test.vb"><![CDATA[ Module Program Sub Main() Test.Goo() Test.Bar() end Sub end module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {ref}) Dim expected = <![CDATA[ BC40000: 'Public Shared Overloads Sub Goo()' is obsolete: 'hello'. Test.Goo() ~~~~~~~~~~ BC40000: 'Public Shared Overloads Sub Bar()' is obsolete: 'hi'. Test.Bar() ~~~~~~~~~~ ]]> compilation2.AssertTheseDiagnostics(expected) Dim source3 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata Module Program <Deprecated("hello", DeprecationType.Deprecate, 1, gettype(integer))> sub Goo() end sub <Deprecated("hi", DeprecationType.Deprecate, 1)> Sub Bar() End sub Sub Main() Goo() Bar() end Sub end module ]]> </file> </compilation> Dim compilation3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {ref}) Dim expected2 = <![CDATA[ BC40000: 'Public Sub Goo()' is obsolete: 'hello'. Goo() ~~~~~ BC40000: 'Public Sub Bar()' is obsolete: 'hi'. Bar() ~~~~~ ]]> compilation3.AssertTheseDiagnostics(expected2) End Sub <Fact> <WorkItem(22447, "https://github.com/dotnet/roslyn/issues/22447")> Public Sub TestRefLikeType() Dim csSource = <![CDATA[ public ref struct S { } ]]> Dim csCompilation = CreateCSharpCompilation("Dll1", csSource.Value, parseOptions:=New CSharp.CSharpParseOptions(CSharp.LanguageVersion.CSharp7_2)) Dim ref = csCompilation.EmitToImageReference() Dim vbSource = <compilation> <file name="test.vb"><![CDATA[ Module Program Sub M(s As S) End Sub End Module ]]> </file> </compilation> Dim vbCompilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, {ref}) vbCompilation.AssertTheseDiagnostics((<![CDATA[ BC30668: 'S' is obsolete: 'Types with embedded references are not supported in this version of your compiler.'. Sub M(s As S) ~ ]]>)) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "S").WithArguments("S", "Types with embedded references are not supported in this version of your compiler.").WithLocation(2, 16) ) End Sub <Fact(), WorkItem(858839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858839")> Public Sub Bug858839_1() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata Public Class MainPage Public Shared Sub Main(args As String()) End Sub Private Shared Sub TestGoo1(a As IGoo1, b As ConcreteGoo1) a.Goo() ' IGoo1 b.Goo() ' ConcreteGoo1 End Sub Private Shared Sub TestGoo2(a As IGoo2, b As ConcreteGoo2) a.Goo() ' IGoo2 b.Goo() ' ConcreteGoo2 End Sub Private Shared Sub TestGoo3(a As IGoo3, b As ConcreteGoo3) a.Goo() ' IGoo3 b.Goo() ' ConcreteGoo3 End Sub End Class Public Interface IGoo1 <Deprecated("IGoo1.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Sub Goo() End Interface Public NotInheritable Class ConcreteGoo1 Implements IGoo1 Public Sub Goo() Implements IGoo1.Goo End Sub End Class Public Interface IGoo2 Sub Goo() End Interface Public NotInheritable Class ConcreteGoo2 Implements IGoo2 <Deprecated("ConcreteGoo2.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Public Sub Goo() Implements IGoo2.Goo End Sub End Class Public Interface IGoo3 <Deprecated("IGoo3.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Sub Goo() End Interface Public NotInheritable Class ConcreteGoo3 Implements IGoo3 <Deprecated("ConcreteGoo3.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Public Sub Goo() Implements IGoo3.Goo End Sub End Class ]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs) Dim expected = <![CDATA[ BC40000: 'Sub Goo()' is obsolete: 'IGoo1.Goo has been deprecated'. a.Goo() ' IGoo1 ~~~~~~~ BC40000: 'Public Sub Goo()' is obsolete: 'ConcreteGoo2.Goo has been deprecated'. b.Goo() ' ConcreteGoo2 ~~~~~~~ BC40000: 'Sub Goo()' is obsolete: 'IGoo3.Goo has been deprecated'. a.Goo() ' IGoo3 ~~~~~~~ BC40000: 'Public Sub Goo()' is obsolete: 'ConcreteGoo3.Goo has been deprecated'. b.Goo() ' ConcreteGoo3 ~~~~~~~ BC40000: 'Sub Goo()' is obsolete: 'IGoo1.Goo has been deprecated'. Public Sub Goo() Implements IGoo1.Goo ~~~~~~~~~~~~~~~~~~~~ ]]> compilation1.AssertTheseDiagnostics(expected) End Sub <Fact(), WorkItem(858839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858839")> Public Sub Bug858839_2() Dim source0 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata public Class IExceptionalInterface Property ExceptionalProp As String <Deprecated("Actually, don't even use the prop at all.", DeprecationType.Remove, 50331648UI)> Get Return String.Empty End Get <Deprecated("Changed my mind; don't put this prop.", DeprecationType.Remove, 33554432UI)> Set(value As String) End Set End Property End Class ]]> </file> </compilation> Dim compilation0 = CreateEmptyCompilationWithReferences(source0, WinRtRefs, TestOptions.ReleaseDll) compilation0.VerifyDiagnostics() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports System Class Test Public Sub F(i As IExceptionalInterface) i.ExceptionalProp = "goo" Console.WriteLine(i.ExceptionalProp) End Sub End Class]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs.Append(New VisualBasicCompilationReference(compilation0))) Dim expected = <![CDATA[ BC30911: 'Set' accessor of 'Public Property ExceptionalProp As String' is obsolete: 'Changed my mind; don't put this prop.'. i.ExceptionalProp = "goo" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30911: 'Get' accessor of 'Public Property ExceptionalProp As String' is obsolete: 'Actually, don't even use the prop at all.'. Console.WriteLine(i.ExceptionalProp) ~~~~~~~~~~~~~~~~~ ]]> compilation1.AssertTheseDiagnostics(expected) Dim compilation2 = CreateEmptyCompilationWithReferences(source1, WinRtRefs.Append(compilation0.EmitToImageReference())) compilation2.AssertTheseDiagnostics(expected) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_ObsoleteAttribute Inherits BasicTestBase <Fact()> Public Sub TestObsoleteAttributeOnTypes() Dim source = <compilation> <file name="test.vb"><![CDATA[ Imports System Module Module1 Dim field1 As Class1 Property Prop1 As Class1 Sub Method1(c As Class1) End Sub Sub Main() Dim c As Class1 = Nothing field1 = c Prop1 = c Method1(New Class1()) Dim x As Mydeleg = Function(i) i End Sub End Module <Obsolete("Do not use this type", True)> Class Class1 End Class <Obsolete("Do not use A1", False)> <A2> Class A1 Inherits Attribute End Class <Obsolete> <A1> Class A2 Inherits Attribute End Class <A1> Class A3 Inherits Attribute End Class Class AttrWithType Inherits Attribute Sub New(t As Type) End Sub End Class <Obsolete> <Another> Class G(Of T, U) End Class <Obsolete> <AttrWithType(GetType(G(Of Integer, AnotherAttribute)))> Class AnotherAttribute Inherits Attribute End Class <AttrWithType(GetType(G(Of Integer, AnotherAttribute)))> Class AnotherAttribute1 Inherits Attribute End Class <System.Obsolete("This message" & " should be concat'ed", Not (False))> <SelfRecursive1> Class SelfRecursive1Attribute Inherits Attribute End Class <Obsolete> Public Delegate Function Mydeleg(x As Integer) As Integer <GooAttribute.BarAttribute.Baz> <Obsolete("Blah")> Class GooAttribute Inherits Attribute Class BazAttribute Inherits Attribute End Class Class BarAttribute Inherits GooAttribute End Class End Class Interface IGoo(Of T) End Interface <Obsolete> Class SelfReferenceInBase Implements IGoo(Of SelfReferenceInBase) End Class Class SelfReferenceInBase1 Implements IGoo(Of SelfReferenceInBase) End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "AnotherAttribute").WithArguments("AnotherAttribute"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "A1").WithArguments("A1", "Do not use A1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "G(Of Integer, AnotherAttribute)").WithArguments("G(Of Integer, AnotherAttribute)"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "SelfReferenceInBase").WithArguments("SelfReferenceInBase"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Class1").WithArguments("Class1", "Do not use this type"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "Mydeleg").WithArguments("Mydeleg")) End Sub <Fact()> Public Sub TestObsoleteAttributeOnMembers() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices Public Class Test Public Shared Sub Main() ObsoleteMethod1() ObsoleteMethod2() ObsoleteMethod3() ObsoleteMethod5() Dim t As Test = New Test() t.ObsoleteMethod4() Dim f = t.field1 Dim p1 = t.Property1 Dim p2 = t.Property2 AddHandler t.event1, Sub() Return t.ObsoleteExtensionMethod1() Dim func As Action(Of Integer) = AddressOf t.ObsoleteMethod4 func(1) Dim func1 As Action = AddressOf t.ObsoleteMethod4 func1() Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} Dim i1 = t1(10) Dim gt As GenericTest(Of Integer) = New GenericTest(Of Integer)() gt.ObsoleteMethod1(Of Double)() Dim gf = gt.field1 Dim gp1 = gt.Property1 AddHandler gt.event1, Sub(i) Return End Sub <Obsolete> Public Shared Sub ObsoleteMethod1() End Sub <Obsolete("Do not call this method")> Public Shared Sub ObsoleteMethod2() End Sub <Obsolete("Do not call this method", True)> Public Shared Sub ObsoleteMethod3() End Sub <Obsolete("Do not call this method")> Public Sub ObsoleteMethod4() End Sub <Obsolete("Do not call this method")> Public Sub ObsoleteMethod4(x As Integer) End Sub <Obsolete(Nothing, True)> Public Shared Sub ObsoleteMethod5() End Sub <Obsolete> Public Sub New() End Sub <Obsolete("Do not use this field")> Public field1 As Integer = 0 <Obsolete("Do not use this property")> Public Property Property1 As Integer <Obsolete("Do not use this property")> Public Property Property2 As Integer Get Return 11 End Get Set(value As Integer) End Set End Property <Obsolete("Do not use this event")> Public Event event1 As Action Public ReadOnly Property Prop2 As Integer <Obsolete> Get Return 10 End Get End Property Public Property Prop3 As Integer Get Return 10 End Get <Obsolete> Set(value As Integer) End Set End Property Public Custom Event event2 As Action <Obsolete> AddHandler(value As Action) End AddHandler <Obsolete> RemoveHandler(value As Action) End RemoveHandler <Obsolete> RaiseEvent() End RaiseEvent End Event <Obsolete> Default Public ReadOnly Property Item(x As Integer) Get Return 10 End Get End Property End Class Public Class GenericTest(Of T) <Obsolete> Public Sub ObsoleteMethod1(Of U)() End Sub <Obsolete("Do not use this field")> Public field1 As T = Nothing <Obsolete("Do not use this property")> Public Property Property1 As T <Obsolete("Do not use this event")> Public Event event1 As Action(Of T) End Class Public Module TestExtension <Obsolete("Do not call this extension method")> <Extension> Public Sub ObsoleteExtensionMethod1(t As Test) End Sub End Module ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {TestMetadata.Net40.SystemCore}).AssertTheseDiagnostics( <![CDATA[ BC40008: 'Public Shared Sub ObsoleteMethod1()' is obsolete. ObsoleteMethod1() ~~~~~~~~~~~~~~~~~ BC40000: 'Public Shared Sub ObsoleteMethod2()' is obsolete: 'Do not call this method'. ObsoleteMethod2() ~~~~~~~~~~~~~~~~~ BC30668: 'Public Shared Sub ObsoleteMethod3()' is obsolete: 'Do not call this method'. ObsoleteMethod3() ~~~~~~~~~~~~~~~~~ BC31075: 'Public Shared Sub ObsoleteMethod5()' is obsolete. ObsoleteMethod5() ~~~~~~~~~~~~~~~~~ BC40008: 'Public Sub New()' is obsolete. Dim t As Test = New Test() ~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4()' is obsolete: 'Do not call this method'. t.ObsoleteMethod4() ~~~~~~~~~~~~~~~~~~~ BC40000: 'Public field1 As Integer' is obsolete: 'Do not use this field'. Dim f = t.field1 ~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim p1 = t.Property1 ~~~~~~~~~~~ BC40000: 'Public Property Property2 As Integer' is obsolete: 'Do not use this property'. Dim p2 = t.Property2 ~~~~~~~~~~~ BC40000: 'Public Event event1 As Action' is obsolete: 'Do not use this event'. AddHandler t.event1, Sub() Return ~~~~~~~~ BC40000: 'Public Sub ObsoleteExtensionMethod1()' is obsolete: 'Do not call this extension method'. t.ObsoleteExtensionMethod1() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4(x As Integer)' is obsolete: 'Do not call this method'. Dim func As Action(Of Integer) = AddressOf t.ObsoleteMethod4 ~~~~~~~~~~~~~~~~~ BC40000: 'Public Sub ObsoleteMethod4()' is obsolete: 'Do not call this method'. Dim func1 As Action = AddressOf t.ObsoleteMethod4 ~~~~~~~~~~~~~~~~~ BC40008: 'Public Sub New()' is obsolete. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~ BC40000: 'Public Property Property2 As Integer' is obsolete: 'Do not use this property'. Dim t1 As Test = New Test With {.Property1 = 10, .Property2 = 20} ~~~~~~~~~ BC40008: 'Public ReadOnly Default Property Item(x As Integer) As Object' is obsolete. Dim i1 = t1(10) ~~~~~~ BC40008: 'Public Sub ObsoleteMethod1(Of Double)()' is obsolete. gt.ObsoleteMethod1(Of Double)() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC40000: 'Public field1 As Integer' is obsolete: 'Do not use this field'. Dim gf = gt.field1 ~~~~~~~~~ BC40000: 'Public Property Property1 As Integer' is obsolete: 'Do not use this property'. Dim gp1 = gt.Property1 ~~~~~~~~~~~~ BC40000: 'Public Event event1 As Action(Of Integer)' is obsolete: 'Do not use this event'. AddHandler gt.event1, Sub(i) Return ~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ BC31142: 'System.ObsoleteAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Obsolete> ~~~~~~~~~~~ ]]>) End Sub <Fact> Public Sub TestObsoleteAttributeOnOperators() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Test Public Shared Sub Main() Dim t As New Test() t = 10 t = CType("10", Test) Dim c As New Test() Dim c1 As Test = -c Dim b1 As Boolean = If(c, True, False) If (c AndAlso c1) Then c1 += c End If End Sub <Obsolete> Public Shared Widening Operator CType(x As Integer) As Test Return New Test() End Operator <Obsolete> Public Shared Narrowing Operator CType(x As String) As Test Return New Test() End Operator <Obsolete> Public Shared Operator -(x As test) As Test Return New Test() End Operator <Obsolete> Public Shared Operator IsTrue(x As Test) As Boolean Return True End Operator <Obsolete> Public Shared Operator IsFalse(x As test) As Boolean Return False End Operator <Obsolete> Public Shared Operator +(x As Test, y As Test) As Test Return New Test() End Operator <Obsolete> Public Shared Operator And(x As Test, y As Test) As Test Return New Test() End Operator End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "10").WithArguments("Public Shared Widening Operator CType(x As Integer) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "CType(""10"", Test)").WithArguments("Public Shared Narrowing Operator CType(x As String) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "-c").WithArguments("Public Shared Operator -(x As Test) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c").WithArguments("Public Shared Operator IsTrue(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c AndAlso c1").WithArguments("Public Shared Operator And(x As Test, y As Test) As Test"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c AndAlso c1").WithArguments("Public Shared Operator IsFalse(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "(c AndAlso c1)").WithArguments("Public Shared Operator IsTrue(x As Test) As Boolean"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "c1 += c").WithArguments("Public Shared Operator +(x As Test, y As Test) As Test")) End Sub <Fact> Public Sub TestObsoleteAttributeInMetadata() Dim peSource = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class TestClass1 End Class <Obsolete("TestClass2 is obsolete")> Public Class TestClass2 End Class <Obsolete("Do not use TestClass3", True)> Public Class TestClass3 End Class <Obsolete("TestClass4 is obsolete", False)> Public Class TestClass4 End Class <Obsolete(Nothing, True)> Public Module TestModule Public Sub TestMethod() End Sub End Module Public Class TestClass <Obsolete("Do not use TestMethod")> Public Sub TestMethod() End Sub <Obsolete("Do not use Prop1", False)> Public Property Prop1 As Integer <Obsolete("Do not use field1", True)> Public field1 As TestClass <Obsolete("Do not use event", True)> Public Event event1 As Action End Class ]]> </file> </compilation> Dim peReference = MetadataReference.CreateFromImage(CreateCompilationWithMscorlib40AndVBRuntime(peSource).EmitToArray()) Dim source = <compilation> <file name="b.vb"><![CDATA[ Public Class Test Public Shared Sub goo1(c As TestClass1) End Sub Public Shared Sub goo2(c As TestClass2) End Sub Public Shared Sub goo3(c As TestClass3) End Sub Public Shared Sub goo4(c As TestClass4) End Sub Public Shared Sub Main() Dim c As TestClass = New TestClass() c.TestMethod() Dim i = c.Prop1 c = c.field1 AddHandler c.event1, Sub() Return TestModule.TestMethod() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndReferences(source, {peReference}).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "TestClass1").WithArguments("TestClass1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "TestClass2").WithArguments("TestClass2", "TestClass2 is obsolete"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "TestClass3").WithArguments("TestClass3", "Do not use TestClass3"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "TestClass4").WithArguments("TestClass4", "TestClass4 is obsolete"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "c.TestMethod()").WithArguments("Public Sub TestMethod()", "Do not use TestMethod"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "c.Prop1").WithArguments("Public Property Prop1 As Integer", "Do not use Prop1"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "c.field1").WithArguments("Public field1 As TestClass", "Do not use field1"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "c.event1").WithArguments("Public Event event1 As System.Action", "Do not use event"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbolNoMessage1, "TestModule").WithArguments("TestModule")) End Sub <Fact> Public Sub TestObsoleteAttributeCycles() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class Test <Obsolete("F1 is obsolete")> <SomeAttr(F1)> Public Const F1 As Integer = 10 <Obsolete("F2 is obsolete", True)> <SomeAttr(F3)> Public Const F2 As Integer = 10 <Obsolete("F3 is obsolete")> <SomeAttr(F2)> Public Const F3 As Integer = 10 <Obsolete(F4, True)> Public Const F4 As String = "blah" <Obsolete(F5)> Public F5 As String = "blah" <Obsolete(P1, True)> Public ReadOnly Property P1 As String Get Return "blah" End Get End Property <Obsolete> <SomeAttr(P2, True)> Public ReadOnly Property P2 As String Get Return "blah" End Get End Property <Obsolete(Method1)> Public Sub Method1() End Sub <Obsolete()> <SomeAttr1(Method2)> Public Sub Method2() End Sub <Obsolete(F6)> <SomeAttr(F6)> <SomeAttr(F7)> Public Const F6 As String = "F6 is obsolete" <Obsolete(F7, True)> <SomeAttr(F6)> <SomeAttr(F7)> Public Const F7 As String = "F7 is obsolete" End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=True)> Public Class SomeAttr Inherits Attribute Public Sub New(x As Integer) End Sub Public Sub New(x As String) End Sub End Class Public Class SomeAttr1 Inherits Attribute Public Sub New(x As Action) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "F5"), Diagnostic(ERRID.ERR_RequiredConstExpr, "F5"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "P1"), Diagnostic(ERRID.ERR_RequiredConstExpr, "P1"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "P2"), Diagnostic(ERRID.ERR_NoArgumentCountOverloadCandidates1, "SomeAttr").WithArguments("New"), Diagnostic(ERRID.ERR_RequiredConstExpr, "P2"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "Method1"), Diagnostic(ERRID.ERR_BadInstanceMemberAccess, "Method2")) End Sub <Fact> Public Sub TestObsoleteAttributeSuppress() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType Public Shared Instance As SomeType Public Const Message As String = "goo" End Class <Obsolete> Module Mod1 Dim someField As SomeType = SomeType.Instance Public Property someProp As SomeType Sub goo(x As SomeType) End Sub End Module Public Class Test <Obsolete> Dim someField As SomeType = SomeType.Instance <Obsolete> Dim someFuncField As Func(Of SomeType) = Function() New SomeType() <Obsolete> Event someEvent As Action(Of SomeType) <Obsolete> Function goo(x As SomeType) As SomeType Dim y As SomeType = New SomeType() Return x End Function End Class <Obsolete> Public Class Base(Of T) End Class <Obsolete> Public Class Derived Inherits Base(Of Base(Of Integer)) End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAttributeSuppress_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType End Class <Obsolete> Public Delegate Sub MyDeleg() Public Class Test <Obsolete> Public Shared Property someProp As SomeType <Obsolete> Default Public Property Item(x As SomeType) As SomeType Get Return Nothing End Get <Obsolete> Set(value As SomeType) Dim y As SomeType = New SomeType() End Set End Property <Obsolete> Custom Event goo As MyDeleg AddHandler(value As MyDeleg) End AddHandler RemoveHandler(value As MyDeleg) End RemoveHandler RaiseEvent() End RaiseEvent End Event <Obsolete()> Public Property Prop1 As SomeType Get Return New SomeType() End Get Set(ByVal Value As SomeType) Dim p As New SomeType() End Set End Property End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAndPropertyAccessors() Dim source = <compilation> <file><![CDATA[ Imports System Namespace Windows.Foundation.Metadata Public NotInheritable Class DeprecatedAttribute Inherits Attribute Public Sub New(message As String, type As DeprecationType, version As UInteger) End Sub End Class Public Enum DeprecationType Deprecate Remove End Enum End Namespace ]]> </file> <file><![CDATA[ Imports Windows.Foundation.Metadata <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class A End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class B End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class C End Class Class D ReadOnly Property P As Object Get Return New A() End Get End Property <Deprecated(Nothing, DeprecationType.Deprecate, 0)>ReadOnly Property Q As Object Get Return New B() End Get End Property ReadOnly Property R As Object <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Get Return New C() End Get End Property End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC40008: 'A' is obsolete. Return New A() ~ ]]></errors>) End Sub <Fact> Public Sub TestObsoleteAndEventAccessors() Dim source = <compilation> <file><![CDATA[ Imports System Namespace Windows.Foundation.Metadata Public NotInheritable Class DeprecatedAttribute Inherits Attribute Public Sub New(message As String, type As DeprecationType, version As UInteger) End Sub End Class Public Enum DeprecationType Deprecate Remove End Enum End Namespace ]]> </file> <file><![CDATA[ Imports System Imports Windows.Foundation.Metadata <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class A End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class B End Class <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Class C End Class Class D Custom Event E As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) M(New A()) End RemoveHandler RaiseEvent End RaiseEvent End Event <Deprecated(Nothing, DeprecationType.Deprecate, 0)>Custom Event F As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) M(New B()) End RemoveHandler RaiseEvent End RaiseEvent End Event Custom Event G As EventHandler AddHandler(value As EventHandler) End AddHandler <Deprecated(Nothing, DeprecationType.Deprecate, 0)>RemoveHandler(value As EventHandler) M(New C()) End RemoveHandler RaiseEvent End RaiseEvent End Event Shared Sub M(o As Object) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC40008: 'A' is obsolete. M(New A()) ~ BC31142: 'Windows.Foundation.Metadata.DeprecatedAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Deprecated(Nothing, DeprecationType.Deprecate, 0)>RemoveHandler(value As EventHandler) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> Public Sub TestObsoleteAttributeCycles_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Goo> Class Goo Inherits Base End Class <Goo> class Base Inherits System.Attribute Public Class Nested Inherits Goo End Class End Class ]]> </file> </compilation> CompileAndVerify(source) source = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> Public Class SomeType Public Shared Instance As SomeType Public Const Message As String = "goo" End Class Public Class SomeAttr Inherits Attribute Public Sub New(message As String) End Sub End Class <Obsolete(SomeType.Message)> Public Class Derived Inherits Base End Class Public Class Base <Obsolete(SomeType.Message)> Public Property SomeProp As SomeType End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithConcurrentBuild(False)).VerifyDiagnostics() End Sub <Fact> Public Sub TestObsoleteAttributeP2PReference() Dim s = <compilation> <file name="a.vb"><![CDATA[ Imports System <Obsolete> public Class C <Obsolete> public sub Goo() end sub end class ]]> </file> </compilation> Dim other = CreateCompilationWithMscorlib40(s) s = <compilation> <file name="b.vb"><![CDATA[ Public Class A Sub New(o As C) o.Goo() end sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndReferences(s, {New VisualBasicCompilationReference(other)}).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "C").WithArguments("C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "o.Goo()").WithArguments("Public Sub Goo()")) End Sub <Fact> Public Sub TestObsoleteAttributeOnMembers2() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 Property p As String <Obsolete("", False)> Get Return "hello" End Get <Obsolete> Set(value As String) End Set End Property <Obsolete> WithEvents p1 As New C2 Sub handler() Handles p1.XEvent End Sub <Obsolete> Sub handler2() Handles p1.XEvent End Sub Custom Event goo As MyDeleg AddHandler(value As MyDeleg) End AddHandler RemoveHandler(value As MyDeleg) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Class C2 <Obsolete> Public Event XEvent() Sub bar(s As String) End Sub Sub goo() Dim s As New C1 s.p += "as" bar(s.p) End Sub End Class <Obsolete> Public Delegate Sub MyDeleg() ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "XEvent").WithArguments("Public Event XEvent()"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "MyDeleg").WithArguments("MyDeleg"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p += ""as""").WithArguments("Set", "Public Property p As String"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p").WithArguments("Get", "Public Property p As String"), Diagnostic(ERRID.WRN_UseOfObsoletePropertyAccessor2, "s.p").WithArguments("Get", "Public Property p As String")) End Sub <Fact> <WorkItem(546636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546636")> Public Sub TestObsoleteAttributeOnAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=True)> Public Class Att Inherits Attribute <Obsolete("Constructor", True)> Public Sub New() End Sub <Obsolete("Property", True)> Public Property Prop As Integer Get Return 1 End Get Set(value As Integer) End Set End Property <Obsolete("Field", True)> Public Field As Integer End Class <Att> <Att(Field:=1)> <Att(Prop:=1)> Public Class Test <Att()> Public Shared Sub Main() End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att()").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Field:=1").WithArguments("Public Field As Integer", "Field"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att(Field:=1)").WithArguments("Public Sub New()", "Constructor"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Prop:=1").WithArguments("Public Property Prop As Integer", "Property"), Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "Att(Prop:=1)").WithArguments("Public Sub New()", "Constructor")) End Sub <Fact> Public Sub TestObsoleteAttributeOnMembers3() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Namespace A.B <Obsolete> Public Class C <Obsolete> Public Shared Field1 As Integer = 10 <Obsolete> Public Class D <Obsolete> Public Shared Field2 As Integer = 20 End Class End Class <Obsolete> Public Class C1 Public Class D End Class End Class <Obsolete> Public Class C2(Of T) <Obsolete> Public Shared Field1 As Integer = 10 Public Class D End Class <Obsolete> Public Class E(Of U) End Class End Class End Namespace Class B(Of T) End Class Class D Inherits B(Of A.B.C1.D) End Class Class D1 Inherits B(Of A.B.C2(Of Integer).D) End Class Class D2 Inherits B(Of A.B.C2(Of Integer).E(Of Integer)) End Class Class Program Shared Sub Main() Dim x = A.B.C.Field1 Dim x1 = A.B.C.D.Field2 Dim y = New A.B.C1.D() Dim y1 = New A.B.C2(Of Integer).D() Dim y2 = A.B.C2(Of Integer).Field1 Dim y3 = New a.b.c2(Of Integer).E(Of Integer) End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C1").WithArguments("A.B.C1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer).E(Of Integer)").WithArguments("A.B.C2(Of Integer).E(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C").WithArguments("A.B.C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.Field1").WithArguments("Public Shared Field1 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C").WithArguments("A.B.C"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.D").WithArguments("A.B.C.D"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C.D.Field2").WithArguments("Public Shared Field2 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C1").WithArguments("A.B.C1"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer)").WithArguments("A.B.C2(Of T)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "A.B.C2(Of Integer).Field1").WithArguments("Public Shared Field1 As Integer"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "a.b.c2(Of Integer)").WithArguments("A.B.C2(Of Integer)"), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "a.b.c2(Of Integer).E(Of Integer)").WithArguments("A.B.C2(Of Integer).E(Of Integer)")) End Sub Private ReadOnly ObsoleteAttributeSource As XElement = <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(message As String) End Sub Public Sub New(message As String, isError As Boolean) End Sub Public Property DiagnosticId As String Public Property UrlFormat As String End Class End Namespace ]]></file> <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="TEST1")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/BC40008", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_03() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}/{1}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_04() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/elementname-is-obsolete-visual-basic-warning")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/elementname-is-obsolete-visual-basic-warning", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadAttribute_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="TEST1")> Sub M1() End Sub Sub M2() M1() End Sub End Class Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(message As String) End Sub Public Sub New(message As String, isError As Boolean) End Sub Public Dim DiagnosticId As String Public Property DiagnosticId As String End Class End Namespace ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify( Diagnostic(ERRID.ERR_MetadataMembersAmbiguous3, "DiagnosticId").WithArguments("DiagnosticId", "class", "System.ObsoleteAttribute").WithLocation(4, 15), Diagnostic(ERRID.ERR_MultiplyDefinedType3, "DiagnosticId").WithArguments("DiagnosticId", "Public DiagnosticId As String", "class").WithLocation(27, 25)) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_05() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1", UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]> </file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("TEST1", diag.Id) Assert.Equal(ERRID.WRN_UseOfObsoleteSymbol2, DirectCast(diag.Code, ERRID)) Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadAttribute_02() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete(DiagnosticId:="A", DiagnosticId:="B", UrlFormat:="C", UrlFormat:="D")> Sub M1() End Sub Sub M2() M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) Dim diags = comp.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Sub M1()").WithLocation(9, 9)) Dim diag = diags.Single() Assert.Equal("C", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_Suppression_01() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1")> Sub M1() End Sub <Obsolete> Sub M2() End Sub Sub M3() M1() M2() #Disable Warning TEST1 M1() M2() #Enable Warning TEST1 #Disable Warning BC40008 M1() M2() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim comp = CreateCompilationWithMscorlib40(source) comp.VerifyDiagnostics( Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(13, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(14, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(18, 9), Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(22, 9)) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_01() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete("don't use", false, DiagnosticId:="TEST1")> Public Sub M1() End Sub <Obsolete> Public Sub M2() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M3() M1() M2() #Disable Warning TEST1 M1() M2() #Enable Warning TEST1 #Disable Warning BC40008 M1() M2() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim expected = { Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(5, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(6, 9), Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M2()").WithArguments("Public Sub M2()").WithLocation(10, 9), Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()", "don't use").WithLocation(14, 9) } Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) comp2.VerifyDiagnostics(expected) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) comp2.VerifyDiagnostics(expected) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_02() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1")> Public Sub M1() End Sub <Obsolete("don't use", DiagnosticId:="TEST2")> Public Sub M2() End Sub <Obsolete("don't use", false, DiagnosticId:="TEST3")> Public Sub M3() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M4() M1() M2() M3() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim expected = { Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9), Diagnostic("TEST2", "M2()").WithArguments("Public Sub M2()", "don't use").WithLocation(6, 9), Diagnostic("TEST3", "M3()").WithArguments("Public Sub M3()", "don't use").WithLocation(7, 9) } Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) comp2.VerifyDiagnostics(expected) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) comp2.VerifyDiagnostics(expected) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_03() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1", UrlFormat:="https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/{0}")> Public Sub M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/compiler-messages/TEST1", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_FromMetadata_04() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:=Nothing, UrlFormat:=Nothing)> Public Sub M1() End Sub End Class ]]></file> <%= ObsoleteAttributeSource %> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_01() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(Flag:=False, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property Flag As Boolean Public Property DiagnosticId As String End Class End Namespace ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_02() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class C1 <Obsolete(DiagnosticId:="TEST1", UrlFormat:="TEST2")> Public Sub M1() End Sub End Class ]]></file> <file name="ObsoleteAttribute.vb"><![CDATA[ Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Dim DiagnosticId As String Public Dim UrlFormat As String End Class End Namespace ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_03() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property ByteProp As Byte Public Property SByteProp As SByte Public Property BooleanProp As Boolean Public Property ShortProp As Short Public Property UshortProp As UShort Public Property CharProp As Char Public Property IntProp As Integer Public Property UintProp As UInteger Public Property FloatProp As Single Public Property LongProp As Long Public Property UlongProp As ULong Public Property DoubleProp As Double Public Property EnumProp As E1 Public Property DiagnosticId As String End Class End Namespace Public Class C1 <Obsolete( ByteProp:=0, SByteProp:=0, BooleanProp:=false, ShortProp:=0, UShortProp:=0, CharProp:="\0", IntProp:=0, UIntProp:=0, FloatProp:=0, LongProp:=0, ULongProp:=0, DoubleProp:=0, EnumProp:=E1.A, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_04() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property IntProp As Integer() Public Property EnumProp As E1() Public Property DiagnosticId As String End Class End Namespace Public Class C1 <Obsolete( IntProp:={0, 1, 2}, EnumProp:={E1.A, E1.B}, DiagnosticId:="TEST1")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("TEST1", "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_05() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Char() Public Property UrlFormat As Char() End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:={"A"}, UrlFormat:={"B"})> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_06() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Char() Public Property UrlFormat As Char() End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:=Nothing, UrlFormat:=Nothing)> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_07() ' In this program C1.M1 has an ObsoleteAttribute with multiple values provided for DiagnosticId and UrlFormat Dim ilSource = " .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig instance void M1() cil managed { .custom instance void System.ObsoleteAttribute::.ctor() = ( 01 00 04 00 // .... 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 41 // T..DiagnosticId.A 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 42 // T..DiagnosticId.B 54 0E 09 55 72 6C 46 6F 72 6D 61 74 01 43 // T..UrlFormat.C 54 0E 09 55 72 6C 46 6F 72 6D 61 74 01 44 ) // T..UrlFormat.D // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C1::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit System.ObsoleteAttribute extends [mscorlib]System.Attribute { .field private string '<DiagnosticId>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field private string '<UrlFormat>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance string get_DiagnosticId() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_DiagnosticId .method public hidebysig specialname instance void set_DiagnosticId(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_DiagnosticId .method public hidebysig specialname instance string get_UrlFormat() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_UrlFormat .method public hidebysig specialname instance void set_UrlFormat(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_UrlFormat .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ObsoleteAttribute::.ctor .property instance string DiagnosticId() { .get instance string System.ObsoleteAttribute::get_DiagnosticId() .set instance void System.ObsoleteAttribute::set_DiagnosticId(string) } // end of property ObsoleteAttribute::DiagnosticId .property instance string UrlFormat() { .get instance string System.ObsoleteAttribute::get_UrlFormat() .set instance void System.ObsoleteAttribute::set_UrlFormat(string) } // end of property ObsoleteAttribute::UrlFormat } // end of class System.ObsoleteAttribute " Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim ilComp = CompileIL(ilSource) Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={ilComp}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Overloads Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("C", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_08() ' In this program C1.M1 has an ObsoleteAttribute with multiple values provided for DiagnosticId and UrlFormat Dim ilSource = " .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .class public auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig instance void M1() cil managed { .custom instance void System.ObsoleteAttribute::.ctor() = ( 01 00 02 00 // .... 54 0E 0C 44 69 61 67 6E 6F 73 74 69 63 49 64 01 41 // T..DiagnosticId.A 0E 09 55 72 6C 46 6F 72 6D 61 74 01 42 ) // ..UrlFormat.B // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method C1::M1 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public auto ansi beforefieldinit System.ObsoleteAttribute extends [mscorlib]System.Attribute { .field private string '<DiagnosticId>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .field private string '<UrlFormat>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname instance string get_DiagnosticId() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_DiagnosticId .method public hidebysig specialname instance void set_DiagnosticId(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<DiagnosticId>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_DiagnosticId .method public hidebysig specialname instance string get_UrlFormat() cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0006: ret } // end of method ObsoleteAttribute::get_UrlFormat .method public hidebysig specialname instance void set_UrlFormat(string 'value') cil managed { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld string System.ObsoleteAttribute::'<UrlFormat>k__BackingField' IL_0007: ret } // end of method ObsoleteAttribute::set_UrlFormat .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method ObsoleteAttribute::.ctor .property instance string DiagnosticId() { .get instance string System.ObsoleteAttribute::get_DiagnosticId() .set instance void System.ObsoleteAttribute::set_DiagnosticId(string) } // end of property ObsoleteAttribute::DiagnosticId .property instance string UrlFormat() { .get instance string System.ObsoleteAttribute::get_UrlFormat() .set instance void System.ObsoleteAttribute::set_UrlFormat(string) } // end of property ObsoleteAttribute::UrlFormat } // end of class System.ObsoleteAttribute " Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim ilComp = CompileIL(ilSource) Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={ilComp}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic("A", "M1()").WithArguments("Public Overloads Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <Fact, WorkItem(42119, "https://github.com/dotnet/roslyn/issues/42119")> Public Sub Obsolete_CustomDiagnosticId_BadMetadata_09() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Enum E1 A B End Enum Namespace System Public Class ObsoleteAttribute Inherits Attribute Public Property DiagnosticId As Object Public Property UrlFormat As Object End Class End Namespace Public Class C1 <Obsolete( DiagnosticId:="A", UrlFormat:="B")> Public Sub M1() End Sub End Class ]]></file> </compilation> Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class C2 Inherits C1 Sub M2() M1() End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilationWithMscorlib40(source1) comp1.VerifyDiagnostics() Dim comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.ToMetadataReference()}) Dim diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) Dim diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) comp2 = CreateCompilationWithMscorlib40(source2, references:={comp1.EmitToImageReference()}) diags = comp2.GetDiagnostics() diags.Verify(Diagnostic(ERRID.WRN_UseOfObsoleteSymbolNoMessage1, "M1()").WithArguments("Public Sub M1()").WithLocation(5, 9)) diag = diags.Single() Assert.Equal("https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(BC40008)", diag.Descriptor.HelpLinkUri) End Sub <WorkItem(578023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578023")> <Fact> Public Sub TestObsoleteInAlias() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports X = C Imports Y = A(Of C) Imports Z = A(Of C()).B Imports C Imports A(Of C) Imports A(Of C()).B Class A(Of T) Friend Class B End Class End Class <System.Obsolete> Class C End Class Module M Private F As X Private G As Y Private H As Z End Module ]]> </file> </compilation>) compilation.AssertTheseDiagnostics(<errors> BC40008: 'C' is obsolete. Imports X = C ~ BC40008: 'C' is obsolete. Imports Y = A(Of C) ~ BC40008: 'C' is obsolete. Imports Z = A(Of C()).B ~ BC40008: 'C' is obsolete. Imports C ~ BC40008: 'C' is obsolete. Imports A(Of C) ~ BC40008: 'C' is obsolete. Imports A(Of C()).B ~ </errors>) End Sub <WorkItem(580832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/580832")> <Fact> Public Sub TestObsoleteOnVirtualMethod() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A <Obsolete("A")> Public Overridable Sub M() End Sub End Class Public Class B Inherits A <Obsolete("B")> Public Overrides Sub M() End Sub Private Sub Base() MyBase.M() End Sub End Class Public Class C Inherits B <Obsolete("C")> Public Overrides Sub M() End Sub Private Sub Test(pa As A, pb As B, pc As C) pa.M() pb.M() pc.M() End Sub Private Sub Base() MyBase.M() End Sub End Class ]]> </file> </compilation>) ' Unlike in C#, VB does not walk up to the least-overridden method. compilation.AssertTheseDiagnostics(<errors> BC40000: 'Public Overridable Sub M()' is obsolete: 'A'. MyBase.M() ~~~~~~~~~~ BC40000: 'Public Overridable Sub M()' is obsolete: 'A'. pa.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'B'. pb.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'C'. pc.M() ~~~~~~ BC40000: 'Public Overrides Sub M()' is obsolete: 'B'. MyBase.M() ~~~~~~~~~~ </errors>) End Sub <Fact()> Public Sub TestDeprecatedAttribute() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata <Deprecated("Class1 is deprecated.", DeprecationType.Deprecate, 0)> public class Class1 End Class <Deprecated("Class2 is deprecated.", DeprecationType.Deprecate, 0, Platform.Windows)> public class Class2 End Class <Deprecated("Class3 is deprecated.", DeprecationType.Remove, 1)> public class Class3 End Class <Deprecated("Class4 is deprecated.", DeprecationType.Remove, 0, Platform.WindowsPhone)> public class Class4 End Class ]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs) compilation1.VerifyDiagnostics() Dim source2 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata class Class5 Sub Test() Dim x1 As Class1 = Nothing Dim x2 As Class2 = Nothing Dim x3 As Class3 = Nothing Dim x4 As Class4 = Nothing Dim x5 As Object x5=x1 x5 = x2 x5 = x3 x5 = x4 End Sub End Class class Class6 Readonly Property P1 As Integer <Deprecated("P1.get is deprecated.", DeprecationType.Remove, 1)> get return 1 End Get End Property Custom Event E1 As System.Action <Deprecated("E1.add is deprecated.", DeprecationType.Remove, 1)> AddHandler(value As System.Action) End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class ]]> </file> </compilation> Dim compilation2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat(New VisualBasicCompilationReference(compilation1))) Dim expected = <![CDATA[ BC40000: 'Class1' is obsolete: 'Class1 is deprecated.'. Dim x1 As Class1 = Nothing ~~~~~~ BC40000: 'Class2' is obsolete: 'Class2 is deprecated.'. Dim x2 As Class2 = Nothing ~~~~~~ BC30668: 'Class3' is obsolete: 'Class3 is deprecated.'. Dim x3 As Class3 = Nothing ~~~~~~ BC30668: 'Class4' is obsolete: 'Class4 is deprecated.'. Dim x4 As Class4 = Nothing ~~~~~~ BC31142: 'Windows.Foundation.Metadata.DeprecatedAttribute' cannot be applied to the 'AddHandler', 'RemoveHandler', or 'RaiseEvent' definitions. If required, apply the attribute directly to the event. <Deprecated("E1.add is deprecated.", DeprecationType.Remove, 1)> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> compilation2.AssertTheseDiagnostics(expected) compilation2 = CreateEmptyCompilationWithReferences(source2, WinRtRefs.Concat(compilation1.EmitToImageReference())) compilation2.AssertTheseDiagnostics(expected) End Sub <Fact()> Public Sub TestDeprecatedAttribute001() Dim source1 = <![CDATA[ using System; using Windows.Foundation.Metadata; namespace Windows.Foundation.Metadata { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true)] public sealed class DeprecatedAttribute : Attribute { public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version) { } public DeprecatedAttribute(System.String message, DeprecationType type, System.UInt32 version, Type contract) { } } public enum DeprecationType { Deprecate = 0, Remove = 1 } } public class Test { [Deprecated("hello", DeprecationType.Deprecate, 1, typeof(int))] public static void Goo() { } [Deprecated("hi", DeprecationType.Deprecate, 1)] public static void Bar() { } } ]]> Dim compilation1 = CreateCSharpCompilation("Dll1", source1.Value) Dim ref = compilation1.EmitToImageReference() Dim source2 = <compilation> <file name="test.vb"><![CDATA[ Module Program Sub Main() Test.Goo() Test.Bar() end Sub end module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {ref}) Dim expected = <![CDATA[ BC40000: 'Public Shared Overloads Sub Goo()' is obsolete: 'hello'. Test.Goo() ~~~~~~~~~~ BC40000: 'Public Shared Overloads Sub Bar()' is obsolete: 'hi'. Test.Bar() ~~~~~~~~~~ ]]> compilation2.AssertTheseDiagnostics(expected) Dim source3 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata Module Program <Deprecated("hello", DeprecationType.Deprecate, 1, gettype(integer))> sub Goo() end sub <Deprecated("hi", DeprecationType.Deprecate, 1)> Sub Bar() End sub Sub Main() Goo() Bar() end Sub end module ]]> </file> </compilation> Dim compilation3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {ref}) Dim expected2 = <![CDATA[ BC40000: 'Public Sub Goo()' is obsolete: 'hello'. Goo() ~~~~~ BC40000: 'Public Sub Bar()' is obsolete: 'hi'. Bar() ~~~~~ ]]> compilation3.AssertTheseDiagnostics(expected2) End Sub <Fact> <WorkItem(22447, "https://github.com/dotnet/roslyn/issues/22447")> Public Sub TestRefLikeType() Dim csSource = <![CDATA[ public ref struct S { } ]]> Dim csCompilation = CreateCSharpCompilation("Dll1", csSource.Value, parseOptions:=New CSharp.CSharpParseOptions(CSharp.LanguageVersion.CSharp7_2)) Dim ref = csCompilation.EmitToImageReference() Dim vbSource = <compilation> <file name="test.vb"><![CDATA[ Module Program Sub M(s As S) End Sub End Module ]]> </file> </compilation> Dim vbCompilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, {ref}) vbCompilation.AssertTheseDiagnostics((<![CDATA[ BC30668: 'S' is obsolete: 'Types with embedded references are not supported in this version of your compiler.'. Sub M(s As S) ~ ]]>)) vbCompilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_UseOfObsoleteSymbol2, "S").WithArguments("S", "Types with embedded references are not supported in this version of your compiler.").WithLocation(2, 16) ) End Sub <Fact(), WorkItem(858839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858839")> Public Sub Bug858839_1() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata Public Class MainPage Public Shared Sub Main(args As String()) End Sub Private Shared Sub TestGoo1(a As IGoo1, b As ConcreteGoo1) a.Goo() ' IGoo1 b.Goo() ' ConcreteGoo1 End Sub Private Shared Sub TestGoo2(a As IGoo2, b As ConcreteGoo2) a.Goo() ' IGoo2 b.Goo() ' ConcreteGoo2 End Sub Private Shared Sub TestGoo3(a As IGoo3, b As ConcreteGoo3) a.Goo() ' IGoo3 b.Goo() ' ConcreteGoo3 End Sub End Class Public Interface IGoo1 <Deprecated("IGoo1.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Sub Goo() End Interface Public NotInheritable Class ConcreteGoo1 Implements IGoo1 Public Sub Goo() Implements IGoo1.Goo End Sub End Class Public Interface IGoo2 Sub Goo() End Interface Public NotInheritable Class ConcreteGoo2 Implements IGoo2 <Deprecated("ConcreteGoo2.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Public Sub Goo() Implements IGoo2.Goo End Sub End Class Public Interface IGoo3 <Deprecated("IGoo3.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Sub Goo() End Interface Public NotInheritable Class ConcreteGoo3 Implements IGoo3 <Deprecated("ConcreteGoo3.Goo has been deprecated", DeprecationType.Deprecate, 0, Platform.Windows)> Public Sub Goo() Implements IGoo3.Goo End Sub End Class ]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs) Dim expected = <![CDATA[ BC40000: 'Sub Goo()' is obsolete: 'IGoo1.Goo has been deprecated'. a.Goo() ' IGoo1 ~~~~~~~ BC40000: 'Public Sub Goo()' is obsolete: 'ConcreteGoo2.Goo has been deprecated'. b.Goo() ' ConcreteGoo2 ~~~~~~~ BC40000: 'Sub Goo()' is obsolete: 'IGoo3.Goo has been deprecated'. a.Goo() ' IGoo3 ~~~~~~~ BC40000: 'Public Sub Goo()' is obsolete: 'ConcreteGoo3.Goo has been deprecated'. b.Goo() ' ConcreteGoo3 ~~~~~~~ BC40000: 'Sub Goo()' is obsolete: 'IGoo1.Goo has been deprecated'. Public Sub Goo() Implements IGoo1.Goo ~~~~~~~~~~~~~~~~~~~~ ]]> compilation1.AssertTheseDiagnostics(expected) End Sub <Fact(), WorkItem(858839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858839")> Public Sub Bug858839_2() Dim source0 = <compilation> <file name="test.vb"><![CDATA[ Imports Windows.Foundation.Metadata public Class IExceptionalInterface Property ExceptionalProp As String <Deprecated("Actually, don't even use the prop at all.", DeprecationType.Remove, 50331648UI)> Get Return String.Empty End Get <Deprecated("Changed my mind; don't put this prop.", DeprecationType.Remove, 33554432UI)> Set(value As String) End Set End Property End Class ]]> </file> </compilation> Dim compilation0 = CreateEmptyCompilationWithReferences(source0, WinRtRefs, TestOptions.ReleaseDll) compilation0.VerifyDiagnostics() Dim source1 = <compilation> <file name="test.vb"><![CDATA[ Imports System Class Test Public Sub F(i As IExceptionalInterface) i.ExceptionalProp = "goo" Console.WriteLine(i.ExceptionalProp) End Sub End Class]]> </file> </compilation> Dim compilation1 = CreateEmptyCompilationWithReferences(source1, WinRtRefs.Append(New VisualBasicCompilationReference(compilation0))) Dim expected = <![CDATA[ BC30911: 'Set' accessor of 'Public Property ExceptionalProp As String' is obsolete: 'Changed my mind; don't put this prop.'. i.ExceptionalProp = "goo" ~~~~~~~~~~~~~~~~~~~~~~~~~ BC30911: 'Get' accessor of 'Public Property ExceptionalProp As String' is obsolete: 'Actually, don't even use the prop at all.'. Console.WriteLine(i.ExceptionalProp) ~~~~~~~~~~~~~~~~~ ]]> compilation1.AssertTheseDiagnostics(expected) Dim compilation2 = CreateEmptyCompilationWithReferences(source1, WinRtRefs.Append(compilation0.EmitToImageReference())) compilation2.AssertTheseDiagnostics(expected) End Sub End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/VSTypeScript/Api/IVSTypeScriptDiagnosticAnalyzerImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(Document document, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Hosting/ObjectFormatter/CommonObjectFormatter.Builder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Object pretty printer. /// </summary> internal abstract partial class CommonObjectFormatter { private sealed class Builder { private readonly StringBuilder _sb; private readonly bool _suppressEllipsis; private readonly BuilderOptions _options; private int _currentLimit; public Builder(BuilderOptions options, bool suppressEllipsis) { _sb = new StringBuilder(); _suppressEllipsis = suppressEllipsis; _options = options; _currentLimit = Math.Min(_options.MaximumLineLength, _options.MaximumOutputLength); } public int Remaining { get { return _options.MaximumOutputLength - _sb.Length; } } // can be negative (the min value is -Ellipsis.Length - 1) private int CurrentRemaining { get { return _currentLimit - _sb.Length; } } public void AppendLine() { // remove line length limit so that we can insert a new line even // if the previous one hit maxed out the line limit: _currentLimit = _options.MaximumOutputLength; Append(_options.NewLine); // recalc limit for the next line: _currentLimit = (int)Math.Min((long)_sb.Length + _options.MaximumLineLength, _options.MaximumOutputLength); } private void AppendEllipsis() { if (_suppressEllipsis) { return; } var ellipsis = _options.Ellipsis; if (string.IsNullOrEmpty(ellipsis)) { return; } _sb.Append(ellipsis); } public void Append(char c, int count = 1) { if (CurrentRemaining < 0) { return; } int length = Math.Min(count, CurrentRemaining); _sb.Append(c, length); if (!_suppressEllipsis && length < count) { AppendEllipsis(); } } public void Append(string str, int start = 0, int count = Int32.MaxValue) { if (str == null || CurrentRemaining < 0) { return; } count = Math.Min(count, str.Length - start); int length = Math.Min(count, CurrentRemaining); _sb.Append(str, start, length); if (!_suppressEllipsis && length < count) { AppendEllipsis(); } } public void AppendFormat(string format, params object[] args) { Append(string.Format(format, args)); } public void AppendGroupOpening() { Append('{'); } public void AppendGroupClosing(bool inline) { if (inline) { Append(" }"); } else { AppendLine(); Append('}'); AppendLine(); } } public void AppendCollectionItemSeparator(bool isFirst, bool inline) { if (isFirst) { if (inline) { Append(' '); } else { AppendLine(); } } else { if (inline) { Append(", "); } else { Append(','); AppendLine(); } } if (!inline) { Append(_options.Indentation); } } /// <remarks> /// This is for conveying cyclic dependencies to the user, not for detecting them. /// </remarks> internal void AppendInfiniteRecursionMarker() { AppendGroupOpening(); AppendCollectionItemSeparator(isFirst: true, inline: true); Append("..."); AppendGroupClosing(inline: true); } public override string ToString() { return _sb.ToString(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Text; namespace Microsoft.CodeAnalysis.Scripting.Hosting { /// <summary> /// Object pretty printer. /// </summary> internal abstract partial class CommonObjectFormatter { private sealed class Builder { private readonly StringBuilder _sb; private readonly bool _suppressEllipsis; private readonly BuilderOptions _options; private int _currentLimit; public Builder(BuilderOptions options, bool suppressEllipsis) { _sb = new StringBuilder(); _suppressEllipsis = suppressEllipsis; _options = options; _currentLimit = Math.Min(_options.MaximumLineLength, _options.MaximumOutputLength); } public int Remaining { get { return _options.MaximumOutputLength - _sb.Length; } } // can be negative (the min value is -Ellipsis.Length - 1) private int CurrentRemaining { get { return _currentLimit - _sb.Length; } } public void AppendLine() { // remove line length limit so that we can insert a new line even // if the previous one hit maxed out the line limit: _currentLimit = _options.MaximumOutputLength; Append(_options.NewLine); // recalc limit for the next line: _currentLimit = (int)Math.Min((long)_sb.Length + _options.MaximumLineLength, _options.MaximumOutputLength); } private void AppendEllipsis() { if (_suppressEllipsis) { return; } var ellipsis = _options.Ellipsis; if (string.IsNullOrEmpty(ellipsis)) { return; } _sb.Append(ellipsis); } public void Append(char c, int count = 1) { if (CurrentRemaining < 0) { return; } int length = Math.Min(count, CurrentRemaining); _sb.Append(c, length); if (!_suppressEllipsis && length < count) { AppendEllipsis(); } } public void Append(string str, int start = 0, int count = Int32.MaxValue) { if (str == null || CurrentRemaining < 0) { return; } count = Math.Min(count, str.Length - start); int length = Math.Min(count, CurrentRemaining); _sb.Append(str, start, length); if (!_suppressEllipsis && length < count) { AppendEllipsis(); } } public void AppendFormat(string format, params object[] args) { Append(string.Format(format, args)); } public void AppendGroupOpening() { Append('{'); } public void AppendGroupClosing(bool inline) { if (inline) { Append(" }"); } else { AppendLine(); Append('}'); AppendLine(); } } public void AppendCollectionItemSeparator(bool isFirst, bool inline) { if (isFirst) { if (inline) { Append(' '); } else { AppendLine(); } } else { if (inline) { Append(", "); } else { Append(','); AppendLine(); } } if (!inline) { Append(_options.Indentation); } } /// <remarks> /// This is for conveying cyclic dependencies to the user, not for detecting them. /// </remarks> internal void AppendInfiniteRecursionMarker() { AppendGroupOpening(); AppendCollectionItemSeparator(isFirst: true, inline: true); Append("..."); AppendGroupClosing(inline: true); } public override string ToString() { return _sb.ToString(); } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/CodeGeneration/Symbols/CodeGenerationEventInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationEventInfo { private static readonly ConditionalWeakTable<IEventSymbol, CodeGenerationEventInfo> s_eventToInfoMap = new(); private readonly bool _isUnsafe; private CodeGenerationEventInfo(bool isUnsafe) => _isUnsafe = isUnsafe; public static void Attach(IEventSymbol @event, bool isUnsafe) { var info = new CodeGenerationEventInfo(isUnsafe); s_eventToInfoMap.Add(@event, info); } private static CodeGenerationEventInfo GetInfo(IEventSymbol @event) { s_eventToInfoMap.TryGetValue(@event, out var info); return info; } public static bool GetIsUnsafe(IEventSymbol @event) => GetIsUnsafe(GetInfo(@event)); private static bool GetIsUnsafe(CodeGenerationEventInfo info) => info != null && info._isUnsafe; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationEventInfo { private static readonly ConditionalWeakTable<IEventSymbol, CodeGenerationEventInfo> s_eventToInfoMap = new(); private readonly bool _isUnsafe; private CodeGenerationEventInfo(bool isUnsafe) => _isUnsafe = isUnsafe; public static void Attach(IEventSymbol @event, bool isUnsafe) { var info = new CodeGenerationEventInfo(isUnsafe); s_eventToInfoMap.Add(@event, info); } private static CodeGenerationEventInfo GetInfo(IEventSymbol @event) { s_eventToInfoMap.TryGetValue(@event, out var info); return info; } public static bool GetIsUnsafe(IEventSymbol @event) => GetIsUnsafe(GetInfo(@event)); private static bool GetIsUnsafe(CodeGenerationEventInfo info) => info != null && info._isUnsafe; } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/SolutionCrawler/NullSolutionCrawlerRegisterationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { /// <summary> /// null implementation of the service. it doesn't do anything since there is no way to observe /// its impact in this layer. /// </summary> [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Default), Shared] internal partial class NullSolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NullSolutionCrawlerRegistrationService() { } public void Register(Workspace workspace) { // base implementation do nothing. } public void Unregister(Workspace workspace, bool blockingShutdown = false) { // base implementation do nothing. } public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata) { // base implementation do nothing. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Mef; namespace Microsoft.CodeAnalysis.SolutionCrawler { /// <summary> /// null implementation of the service. it doesn't do anything since there is no way to observe /// its impact in this layer. /// </summary> [ExportWorkspaceService(typeof(ISolutionCrawlerRegistrationService), ServiceLayer.Default), Shared] internal partial class NullSolutionCrawlerRegistrationService : ISolutionCrawlerRegistrationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NullSolutionCrawlerRegistrationService() { } public void Register(Workspace workspace) { // base implementation do nothing. } public void Unregister(Workspace workspace, bool blockingShutdown = false) { // base implementation do nothing. } public void AddAnalyzerProvider(IIncrementalAnalyzerProvider provider, IncrementalAnalyzerProviderMetadata metadata) { // base implementation do nothing. } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/VisualBasic/Tests/UpdateLegacySuppressions/UpdateLegacySuppressionsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UpdateLegacySuppressions <Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)> <WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")> Public Class UpdateLegacySuppressionsTests <Theory, CombinatorialData> Public Sub TestStandardProperty([property] As AnalyzerProperty) VerifyVB.VerifyStandardProperty([property]) End Sub <Theory> <InlineData("namespace", "N", "~N:N")> <InlineData("type", "N.C+D", "~T:N.C.D")> <InlineData("member", "N.C.#F", "~F:N.C.F")> <InlineData("member", "N.C.#P", "~P:N.C.P")> <InlineData("member", "N.C.#M", "~M:N.C.M")> <InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")> <InlineData("member", "e:N.C.#E", "~E:N.C.E")> Public Async Function LegacySuppressions(scope As String, target As String, fixedTarget As String) As Task Dim input = $" <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope:=""{scope}"", Target:={{|#0:""{target}""|}})> Namespace N Class C Private F As Integer Public Property P As Integer Public Sub M() End Sub Public Function M2(Of T)(tParam As T) As Integer Return 0 End Function Public Event E As System.EventHandler(Of Integer) Class D End Class End Class End Namespace " Dim expectedDiagnostic = VerifyVB.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor). WithLocation(0). WithArguments(target) Dim fixedCode = $" <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope:=""{scope}"", Target:=""{fixedTarget}"")> Namespace N Class C Private F As Integer Public Property P As Integer Public Sub M() End Sub Public Function M2(Of T)(tParam As T) As Integer Return 0 End Function Public Event E As System.EventHandler(Of Integer) Class D End Class End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode) 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.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions.VisualBasicRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer, Microsoft.CodeAnalysis.UpdateLegacySuppressions.UpdateLegacySuppressionsCodeFixProvider) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.UpdateLegacySuppressions <Trait(Traits.Feature, Traits.Features.CodeActionsUpdateLegacySuppressions)> <WorkItem(44362, "https://github.com/dotnet/roslyn/issues/44362")> Public Class UpdateLegacySuppressionsTests <Theory, CombinatorialData> Public Sub TestStandardProperty([property] As AnalyzerProperty) VerifyVB.VerifyStandardProperty([property]) End Sub <Theory> <InlineData("namespace", "N", "~N:N")> <InlineData("type", "N.C+D", "~T:N.C.D")> <InlineData("member", "N.C.#F", "~F:N.C.F")> <InlineData("member", "N.C.#P", "~P:N.C.P")> <InlineData("member", "N.C.#M", "~M:N.C.M")> <InlineData("member", "N.C.#M2(!!0)", "~M:N.C.M2``1(``0)~System.Int32")> <InlineData("member", "e:N.C.#E", "~E:N.C.E")> Public Async Function LegacySuppressions(scope As String, target As String, fixedTarget As String) As Task Dim input = $" <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope:=""{scope}"", Target:={{|#0:""{target}""|}})> Namespace N Class C Private F As Integer Public Property P As Integer Public Sub M() End Sub Public Function M2(Of T)(tParam As T) As Integer Return 0 End Function Public Event E As System.EventHandler(Of Integer) Class D End Class End Class End Namespace " Dim expectedDiagnostic = VerifyVB.Diagnostic(AbstractRemoveUnnecessaryAttributeSuppressionsDiagnosticAnalyzer.LegacyFormatTargetDescriptor). WithLocation(0). WithArguments(target) Dim fixedCode = $" <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""Category"", ""Id: Title"", Scope:=""{scope}"", Target:=""{fixedTarget}"")> Namespace N Class C Private F As Integer Public Property P As Integer Public Sub M() End Sub Public Function M2(Of T)(tParam As T) As Integer Return 0 End Function Public Event E As System.EventHandler(Of Integer) Class D End Class End Class End Namespace " Await VerifyVB.VerifyCodeFixAsync(input, expectedDiagnostic, fixedCode) End Function End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Classification/SyntacticClassifierTests.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.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification <Trait(Traits.Feature, Traits.Features.Classification)> Public Class SyntacticClassifierTests Inherits AbstractVisualBasicClassifierTests Protected Overrides Async Function GetClassificationSpansAsync(code As String, span As TextSpan, parseOptions As ParseOptions, testHost As TestHost) As Task(Of ImmutableArray(Of ClassifiedSpan)) Using workspace = CreateWorkspace(code, testHost) Dim document = workspace.CurrentSolution.Projects.First().Documents.First() Return Await GetSyntacticClassificationsAsync(document, span) End Using End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo", testHost, VBXmlDelimiter("<"), VBXmlName("goo")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.", testHost, VBXmlDelimiter("<"), VBXmlName("goo.")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.b", testHost, VBXmlDelimiter("<"), VBXmlName("goo.b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.b>", testHost, VBXmlDelimiter("<"), VBXmlName("goo.b"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName8(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName9(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:b>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("b"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo. />", testHost, VBXmlDelimiter("<"), VBXmlName("goo."), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo: />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo ba", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("ba")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("=")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("b" & vbCrLf)) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba" & vbCrLf)) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""b""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("b"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValueMultiple1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba"" baz="""" ", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("baz"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValueMultiple2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba"" baz=""a"" ", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("baz"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("a"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent1(testHost As TestHost) As Task Await TestInExpressionAsync("<f>&l</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEntityReference("&"), VBXmlText("l"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent2(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent3(testHost As TestHost) As Task Await TestInExpressionAsync("<f>&#x03C0;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEntityReference("&#x03C0;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent4(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &#x03C0;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&#x03C0;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent5(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent6(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt; bar</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;"), VBXmlText(" bar"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent7(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt;", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData1(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[bar]]></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("bar"), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData4(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[bar]]>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("bar"), VBXmlDelimiter("]]>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData5(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[<>/]]>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("<>/"), VBXmlDelimiter("]]>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData6(testHost As TestHost) As Task Dim code = "<f><![CDATA[goo baz]]></f>" Await TestInExpressionAsync(code, testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("goo" & vbCrLf), VBXmlCDataSection("baz"), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= ", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%=")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar.Baz() %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Baz"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar.Baz() %> />", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Baz"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName6(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %> />", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %> />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), Operators.GreaterThan) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz %> >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz.Goo %> >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent1(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar %></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent2(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar.Goo %></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent3(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar.Goo %> jaz</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlText(" jaz"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContentNested(testHost As TestHost) As Task Dim code = "Dim doc = _ <goo> <%= <bug141> <a>hello</a> </bug141> %> </goo>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("doc"), Operators.Equals, LineContinuation, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), VBXmlDelimiter("<"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContentNestedCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim doc = _ ' Test <goo> <%= <bug141> <a>hello</a> </bug141> %> </goo>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("doc"), Operators.Equals, LineContinuation, Comment("' Test"), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), VBXmlDelimiter("<"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiteralsInLambdas(testHost As TestHost) As Task Dim code = "Dim x = Function() _ <element val=""something""/> Dim y = Function() <element val=""something""/>" Await TestAsync(code, testHost, Keyword("Dim"), Field("x"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), Keyword("Dim"), Field("y"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiteralsInLambdasCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim x = Function() _ 'Test <element val=""something""/> Dim y = Function() <element val=""something""/>" Await TestAsync(code, testHost, Keyword("Dim"), Field("x"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Comment("'Test"), VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), Keyword("Dim"), Field("y"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocumentPrologue(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("encoding"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("UTF-8"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("standalone"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("yes"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals1(testHost As TestHost) As Task Dim code = "Dim a = <Customer id1=""1"" id2=""2"" id3=<%= n2 %> id4=""""> <!-- This is a simple Xml element with all of the node types --> <Name>Me</Name> <NameUsingExpression><%= n1 %></NameUsingExpression> <Street>10802 177th CT NE</Street> <Misc><![CDATA[Let's add some CDATA for fun. ]]> </Misc> <Empty><%= Nothing %></Empty> </Customer>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("a"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("id1"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id2"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id3"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("n2"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("id4"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment(" This is a simple Xml element with all of the node types "), VBXmlDelimiter("-->"), VBXmlDelimiter("<"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlText("Me"), VBXmlDelimiter("</"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("n1"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlText("10802 177th CT NE"), VBXmlDelimiter("</"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("Let's add some CDATA" & Environment.NewLine), VBXmlCDataSection(" for fun. "), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Keyword("Nothing"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals2(testHost As TestHost) As Task Dim code = "Dim b = <?xml version=""1.0""?> <!-- comment before the root --> <?my-PI PI before the root ?> <p:Customer id1=""1"" id2=""2"" id3=<%= n2 %> id4=""""> <!-- This is a simple Xml element with all of the node types --> <q:Name>Me</q:Name> <s:NameUsingExpression><%= n1 %></s:NameUsingExpression> <t:Street>10802 177th CT NE</t:Street> <p:Misc><![CDATA[Let's add some CDATA for fun. ]]> </p:Misc> <Empty><%= Nothing %></Empty> <entity>hello&#x7b;world</entity> </p:Customer>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("b"), Operators.Equals, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<!--"), VBXmlComment(" comment before the root "), VBXmlDelimiter("-->"), VBXmlDelimiter("<?"), VBXmlName("my-PI"), VBXmlProcessingInstruction("PI before the root "), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Customer"), VBXmlAttributeName("id1"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id2"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id3"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("n2"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("id4"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment(" This is a simple Xml element with all of the node types "), VBXmlDelimiter("-->"), VBXmlDelimiter("<"), VBXmlName("q"), VBXmlName(":"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlText("Me"), VBXmlDelimiter("</"), VBXmlName("q"), VBXmlName(":"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("s"), VBXmlName(":"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("n1"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("s"), VBXmlName(":"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("t"), VBXmlName(":"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlText("10802 177th CT NE"), VBXmlDelimiter("</"), VBXmlName("t"), VBXmlName(":"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("Let's add some CDATA for fun. "), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Keyword("Nothing"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("entity"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlEntityReference("&#x7b;"), VBXmlText("world"), VBXmlDelimiter("</"), VBXmlName("entity"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Customer"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals3(testHost As TestHost) As Task Dim code = "Dim c = <p:x xmlns:p=""abc 123""/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("c"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("x"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("p"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("abc" & vbCrLf), VBXmlAttributeValue("123"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals4(testHost As TestHost) As Task Dim code = "Dim d = _ <?xml version=""1.0""?> <a/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("d"), Operators.Equals, LineContinuation, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals4CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim d = _ ' Test <?xml version=""1.0""?> <a/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("d"), Operators.Equals, LineContinuation, Comment("' Test"), VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals5(testHost As TestHost) As Task Dim code = "Dim i = 100 Process( _ <Customer ID=<%= i + 1000 %> a=""""> </Customer>)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, Number("100"), Identifier("Process"), Punctuation.OpenParen, LineContinuation, VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("ID"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("i"), Operators.Plus, Number("1000"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("a"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals5CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim i = 100 Process( _ ' Test <Customer ID=<%= i + 1000 %> a=""""> </Customer>)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, Number("100"), Identifier("Process"), Punctuation.OpenParen, LineContinuation, Comment("' Test"), VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("ID"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("i"), Operators.Plus, Number("1000"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("a"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals6(testHost As TestHost) As Task Dim code = "Dim xmlwithkeywords = <MODULE> <CLASS> <FUNCTION> <DIM i=""1""/> <FOR j=""1"" to=""i""> <NEXT/> </FOR> <END/> </FUNCTION> </CLASS> </MODULE>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("xmlwithkeywords"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("MODULE"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("CLASS"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("FUNCTION"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("DIM"), VBXmlAttributeName("i"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), VBXmlDelimiter("<"), VBXmlName("FOR"), VBXmlAttributeName("j"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("to"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("i"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("NEXT"), VBXmlDelimiter("/>"), VBXmlDelimiter("</"), VBXmlName("FOR"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("END"), VBXmlDelimiter("/>"), VBXmlDelimiter("</"), VBXmlName("FUNCTION"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("CLASS"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("MODULE"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals7(testHost As TestHost) As Task Dim code = "Dim spacetest = <a b=""1"" c=""2""> </a>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("spacetest"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlAttributeName("b"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("c"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestOptionKeywordsInClassContext(testHost As TestHost) As Task Dim code = "Class OptionNoContext Dim Infer Dim Explicit Dim Strict Dim Off Dim Compare Dim Text Dim Binary End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("OptionNoContext"), Keyword("Dim"), Field("Infer"), Keyword("Dim"), Field("Explicit"), Keyword("Dim"), Field("Strict"), Keyword("Dim"), Field("Off"), Keyword("Dim"), Field("Compare"), Keyword("Dim"), Field("Text"), Keyword("Dim"), Field("Binary"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestOptionInferAndExplicit(testHost As TestHost) As Task Dim text = "Option Infer On Option Explicit Off" Await TestAsync(text, testHost, Keyword("Option"), Keyword("Infer"), Keyword("On"), Keyword("Option"), Keyword("Explicit"), Keyword("Off")) End Function <Theory, CombinatorialData> Public Async Function TestOptionCompareTextBinary(testHost As TestHost) As Task Dim code = "Option Compare Text ' comment Option Compare Binary " Await TestAsync(code, testHost, Keyword("Option"), Keyword("Compare"), Keyword("Text"), Comment("' comment"), Keyword("Option"), Keyword("Compare"), Keyword("Binary")) End Function <Theory, CombinatorialData> Public Async Function TestOptionInfer1(testHost As TestHost) As Task Await TestAsync("Option Infer", testHost, Keyword("Option"), Keyword("Infer")) End Function <Theory, CombinatorialData> Public Async Function TestOptionExplicit1(testHost As TestHost) As Task Await TestAsync("Option Explicit", testHost, Keyword("Option"), Keyword("Explicit")) End Function <Theory, CombinatorialData> Public Async Function TestOptionStrict1(testHost As TestHost) As Task Await TestAsync("Option Strict", testHost, Keyword("Option"), Keyword("Strict")) End Function <Theory, CombinatorialData> Public Async Function TestLinqContextualKeywords(testHost As TestHost) As Task Dim code = "Dim from = 0 Dim aggregate = 0 Dim ascending = 0 Dim descending = 0 Dim distinct = 0 Dim by = 0 Shadows equals = 0 Dim group = 0 Dim into = 0 Dim join = 0 Dim skip = 0 Dim take = 0 Dim where = 0 Dim order = 0" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("from"), Operators.Equals, Number("0"), Keyword("Dim"), Field("aggregate"), Operators.Equals, Number("0"), Keyword("Dim"), Field("ascending"), Operators.Equals, Number("0"), Keyword("Dim"), Field("descending"), Operators.Equals, Number("0"), Keyword("Dim"), Field("distinct"), Operators.Equals, Number("0"), Keyword("Dim"), Field("by"), Operators.Equals, Number("0"), Keyword("Shadows"), Field("equals"), Operators.Equals, Number("0"), Keyword("Dim"), Field("group"), Operators.Equals, Number("0"), Keyword("Dim"), Field("into"), Operators.Equals, Number("0"), Keyword("Dim"), Field("join"), Operators.Equals, Number("0"), Keyword("Dim"), Field("skip"), Operators.Equals, Number("0"), Keyword("Dim"), Field("take"), Operators.Equals, Number("0"), Keyword("Dim"), Field("where"), Operators.Equals, Number("0"), Keyword("Dim"), Field("order"), Operators.Equals, Number("0")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression1(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goo", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goo")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression2(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goofooo.Goo", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goofooo"), Operators.Dot, Identifier("Goo")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression3(testHost As TestHost) As Task Await TestInExpressionAsync("From it ", testHost, Keyword("From"), Identifier("it")) End Function <Theory, CombinatorialData> Public Async Function TestFromNotInContext1(testHost As TestHost) As Task Dim code = "Class From End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("From"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestFromNotInContext2(testHost As TestHost) As Task Await TestInMethodAsync("Dim from = 42", testHost, Keyword("Dim"), Local("from"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestWhereLinqExpression1(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goo Where it <> 4", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("Where"), Identifier("it"), Operators.LessThanGreaterThan, Number("4")) End Function <Theory, CombinatorialData> Public Async Function TestLinqQuery1(testHost As TestHost) As Task Dim code = "Dim src = New List(Of Boolean) Dim var3 = 1 Dim q = From var1 In src Where var1 And True _ Order By var1 Ascending Order By var1 Descending _ Select var1 Distinct _ Join var2 In src On var1 Equals var2 _ Skip var3 Skip While var3 Take var3 Take While var3 _ Aggregate var4 In src _ Group var4 By var4 Into var5 = Count() _ Group Join var6 In src On var6 Equals var5 Into var7 Into var8 = Count()" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("src"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("Dim"), Local("var3"), Operators.Equals, Number("1"), Keyword("Dim"), Local("q"), Operators.Equals, Keyword("From"), Identifier("var1"), Keyword("In"), Identifier("src"), Keyword("Where"), Identifier("var1"), Keyword("And"), Keyword("True"), LineContinuation, Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Ascending"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Descending"), LineContinuation, Keyword("Select"), Identifier("var1"), Keyword("Distinct"), LineContinuation, Keyword("Join"), Identifier("var2"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var1"), Keyword("Equals"), Identifier("var2"), LineContinuation, Keyword("Skip"), Identifier("var3"), Keyword("Skip"), Keyword("While"), Identifier("var3"), Keyword("Take"), Identifier("var3"), Keyword("Take"), Keyword("While"), Identifier("var3"), LineContinuation, Keyword("Aggregate"), Identifier("var4"), Keyword("In"), Identifier("src"), LineContinuation, Keyword("Group"), Identifier("var4"), Keyword("By"), Identifier("var4"), Keyword("Into"), Identifier("var5"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Keyword("Group"), Keyword("Join"), Identifier("var6"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var6"), Keyword("Equals"), Identifier("var5"), Keyword("Into"), Identifier("var7"), Keyword("Into"), Identifier("var8"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestLinqQuery1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim src = New List(Of Boolean) Dim var3 = 1 Dim q = From var1 In src Where var1 And True _ ' Test 1 space Order By var1 Ascending Order By var1 Descending _ ' Test 2 space Select var1 Distinct _ ' Test 3 space Join var2 In src On var1 Equals var2 _ ' Test 4 space Skip var3 Skip While var3 Take var3 Take While var3 _ ' Test 1 space Aggregate var4 In src _ ' Test 1 space Group var4 By var4 Into var5 = Count() _ ' Test 1 space Group Join var6 In src On var6 Equals var5 Into var7 Into var8 = Count()" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("src"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("Dim"), Local("var3"), Operators.Equals, Number("1"), Keyword("Dim"), Local("q"), Operators.Equals, Keyword("From"), Identifier("var1"), Keyword("In"), Identifier("src"), Keyword("Where"), Identifier("var1"), Keyword("And"), Keyword("True"), LineContinuation, Comment("' Test 1 space"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Ascending"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Descending"), LineContinuation, Comment("' Test 2 space"), Keyword("Select"), Identifier("var1"), Keyword("Distinct"), LineContinuation, Comment("' Test 3 space"), Keyword("Join"), Identifier("var2"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var1"), Keyword("Equals"), Identifier("var2"), LineContinuation, Comment("' Test 4 space"), Keyword("Skip"), Identifier("var3"), Keyword("Skip"), Keyword("While"), Identifier("var3"), Keyword("Take"), Identifier("var3"), Keyword("Take"), Keyword("While"), Identifier("var3"), LineContinuation, Comment("' Test 1 space"), Keyword("Aggregate"), Identifier("var4"), Keyword("In"), Identifier("src"), LineContinuation, Comment("' Test 1 space"), Keyword("Group"), Identifier("var4"), Keyword("By"), Identifier("var4"), Keyword("Into"), Identifier("var5"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Comment("' Test 1 space"), Keyword("Group"), Keyword("Join"), Identifier("var6"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var6"), Keyword("Equals"), Identifier("var5"), Keyword("Into"), Identifier("var7"), Keyword("Into"), Identifier("var8"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <WorkItem(542387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542387")> <Theory, CombinatorialData> Public Async Function TestFromInQuery(testHost As TestHost) As Task Dim code = "Dim From = New List(Of Integer) Dim result = From s In From Select s" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("From"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("Dim"), Local("result"), Operators.Equals, Keyword("From"), Identifier("s"), Keyword("In"), Identifier("From"), Keyword("Select"), Identifier("s")) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword1(testHost As TestHost) As Task Dim code = "Dim Value = ""Test"" Dim Key As String = Key.Length & (Key.Length) Dim Array As String() = { Key, Key.Length } Dim o = New With {Key Key.Length, Key .Id = 1, Key Key, Key Value, Key.Empty} o = New With {Key _ Key.Length, _ Key _ .Id = 1, _ Key _ Key, _ Key _ Value, _ Key Key. _ Empty _ }" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("Value"), Operators.Equals, [String]("""Test"""), Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("String"), Operators.Equals, Identifier("Key"), Operators.Dot, Identifier("Length"), Operators.Ampersand, Punctuation.OpenParen, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Keyword("Dim"), Local("Array"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Punctuation.Comma, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseCurly, Keyword("Dim"), Local("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, Keyword("Key"), Identifier("Key"), Punctuation.Comma, Keyword("Key"), Identifier("Value"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Empty"), Punctuation.CloseCurly, Identifier("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), LineContinuation, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Identifier("Key"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Identifier("Value"), Punctuation.Comma, LineContinuation, Keyword("Key"), Identifier("Key"), Operators.Dot, LineContinuation, Identifier("Empty"), LineContinuation, Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim Value = ""Test"" Dim Key As String = Key.Length & (Key.Length) Dim Array As String() = { Key, Key.Length } Dim o = New With {Key Key.Length, Key .Id = 1, Key Key, Key Value, Key.Empty} o = New With {Key _ ' Test Key.Length, _ ' Test Key _ ' Test .Id = 1, _ ' Test Key _ ' Test Key, _ ' Test Key _ ' Test Value, _ ' Test Key Key. _ ' Test Empty _ ' Test }" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("Value"), Operators.Equals, [String]("""Test"""), Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("String"), Operators.Equals, Identifier("Key"), Operators.Dot, Identifier("Length"), Operators.Ampersand, Punctuation.OpenParen, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Keyword("Dim"), Local("Array"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Punctuation.Comma, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseCurly, Keyword("Dim"), Local("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, Keyword("Key"), Identifier("Key"), Punctuation.Comma, Keyword("Key"), Identifier("Value"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Empty"), Punctuation.CloseCurly, Identifier("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Key"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Value"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), Identifier("Key"), Operators.Dot, LineContinuation, Comment("' Test"), Identifier("Empty"), LineContinuation, Comment("' Test"), Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword2(testHost As TestHost) As Task Dim code = "Dim k = 10 Dim x = New With {Key If(k > 3, 2, -2).GetTypeCode} Dim y = New With {Key DirectCast(New Object(), Integer).GetTypeCode} Dim z1 = New With {Key If(True, 1,2).GetTypeCode()} Dim z2 = New With {Key CType(Nothing, Integer).GetTypeCode()} Dim Key As Integer If Key Or True Or Key = 1 Then Console.WriteLine() Dim z3() = { Key Or True, Key = 1 } Dim z4 = New List(Of Integer) From {1, 2, 3} Dim z5 As New List(Of Integer) From {1, 2, 3} Dim z6 = New List(Of Integer) With {.Capacity = 2}" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("k"), Operators.Equals, Number("10"), Keyword("Dim"), Local("x"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), ControlKeyword("If"), Punctuation.OpenParen, Identifier("k"), Operators.GreaterThan, Number("3"), Punctuation.Comma, Number("2"), Punctuation.Comma, Operators.Minus, Number("2"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.CloseCurly, Keyword("Dim"), Local("y"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Keyword("DirectCast"), Punctuation.OpenParen, Keyword("New"), Keyword("Object"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Comma, Keyword("Integer"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.CloseCurly, Keyword("Dim"), Local("z1"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), ControlKeyword("If"), Punctuation.OpenParen, Keyword("True"), Punctuation.Comma, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Keyword("Dim"), Local("z2"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Keyword("CType"), Punctuation.OpenParen, Keyword("Nothing"), Punctuation.Comma, Keyword("Integer"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("Integer"), ControlKeyword("If"), Identifier("Key"), Keyword("Or"), Keyword("True"), Keyword("Or"), Identifier("Key"), Operators.Equals, Number("1"), ControlKeyword("Then"), Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("z3"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Keyword("Or"), Keyword("True"), Punctuation.Comma, Identifier("Key"), Operators.Equals, Number("1"), Punctuation.CloseCurly, Keyword("Dim"), Local("z4"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("From"), Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.CloseCurly, Keyword("Dim"), Local("z5"), Keyword("As"), Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("From"), Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.CloseCurly, Keyword("Dim"), Local("z6"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("With"), Punctuation.OpenCurly, Operators.Dot, Identifier("Capacity"), Operators.Equals, Number("2"), Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestNamespaceDeclaration(testHost As TestHost) As Task Dim code = "Namespace N1.N2 End Namespace" Await TestAsync(code, testHost, Keyword("Namespace"), [Namespace]("N1"), Operators.Dot, [Namespace]("N2"), Keyword("End"), Keyword("Namespace")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration1(testHost As TestHost) As Task Dim code = "Class C1" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration2(testHost As TestHost) As Task Dim code = "Class C1 End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration3(testHost As TestHost) As Task Dim code = "Class C1 : End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Punctuation.Colon, Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration1(testHost As TestHost) As Task Dim code = "Structure S1" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration2(testHost As TestHost) As Task Dim code = "Structure S1 : End Structure" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1"), Punctuation.Colon, Keyword("End"), Keyword("Structure")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration3(testHost As TestHost) As Task Dim code = "Structure S1 End Structure" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1"), Keyword("End"), Keyword("Structure")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration1(testHost As TestHost) As Task Dim code = "Interface I1" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration2(testHost As TestHost) As Task Dim code = "Interface I1 : End Interface" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1"), Punctuation.Colon, Keyword("End"), Keyword("Interface")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration3(testHost As TestHost) As Task Dim code = "Interface I1 End Interface" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1"), Keyword("End"), Keyword("Interface")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration1(testHost As TestHost) As Task Dim code = "Enum E1" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration2(testHost As TestHost) As Task Dim code = "Enum E1 : End Enum" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1"), Punctuation.Colon, Keyword("End"), Keyword("Enum")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration3(testHost As TestHost) As Task Dim code = "Enum E1 End Enum" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1"), Keyword("End"), Keyword("Enum")) End Function <Theory, CombinatorialData> Public Async Function TestDelegateSubDeclaration1(testHost As TestHost) As Task Dim code = "Public Delegate Sub Goo()" Await TestAsync(code, testHost, Keyword("Public"), Keyword("Delegate"), Keyword("Sub"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestDelegateFunctionDeclaration1(testHost As TestHost) As Task Dim code = "Public Delegate Function Goo() As Integer" Await TestAsync(code, testHost, Keyword("Public"), Keyword("Delegate"), Keyword("Function"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestTernaryConditionalExpression(testHost As TestHost) As Task Dim code = "Dim i = If(True, 1, 2)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, ControlKeyword("If"), Punctuation.OpenParen, Keyword("True"), Punctuation.Comma, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestForStatement(testHost As TestHost) As Task Dim code = "For i = 0 To 10 Exit For" Await TestInMethodAsync(code, testHost, ControlKeyword("For"), Identifier("i"), Operators.Equals, Number("0"), ControlKeyword("To"), Number("10"), ControlKeyword("Exit"), ControlKeyword("For")) End Function <Theory, CombinatorialData> Public Async Function TestFloatLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("1.0", testHost, Number("1.0")) End Function <Theory, CombinatorialData> Public Async Function TestIntLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("1", testHost, Number("1")) End Function <Theory, CombinatorialData> Public Async Function TestDecimalLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("123D", testHost, Number("123D")) End Function <Theory, CombinatorialData> Public Async Function TestStringLiterals1(testHost As TestHost) As Task Await TestInExpressionAsync("""goo""", testHost, [String]("""goo""")) End Function <Theory, CombinatorialData> Public Async Function TestCharacterLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("""f""c", testHost, [String]("""f""c")) End Function <Theory, CombinatorialData> Public Async Function TestRegression_DoUntil1(testHost As TestHost) As Task Dim code = "Do Until True" Await TestInMethodAsync(code, testHost, ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True")) End Function <Theory, CombinatorialData> Public Async Function TestComment1(testHost As TestHost) As Task Dim code = "'goo" Await TestAsync(code, testHost, Comment("'goo")) End Function <Theory, CombinatorialData> Public Async Function TestComment2(testHost As TestHost) As Task Dim code = "Class C1 'hello" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Comment("'hello")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_SingleLine(testHost As TestHost) As Task Dim code = "'''<summary>something</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_ExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary> ''' something ''' </summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" something"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_ExteriorTriviaInsideEndTag(testHost As TestHost) As Task Dim code = "''' <summary></ ''' summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("'''"), XmlDoc.Name(" "), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_AttributesWithExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary att1=""value1"" ''' att2=""value2""> ''' something ''' </summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Name(" "), XmlDoc.AttributeName("att1"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value1"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter("'''"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("att2"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value2"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" something"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_EmptyElementAttributesWithExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary att1=""value1"" ''' att2=""value2"" /> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Name(" "), XmlDoc.AttributeName("att1"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value1"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter("'''"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("att2"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value2"), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeQuotes(" "), XmlDoc.Delimiter("/>"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_XmlCommentWithExteriorTrivia(testHost As TestHost) As Task Dim code = "'''<summary> '''<!--first '''second--> '''</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first" & vbCrLf), XmlDoc.Delimiter("'''"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_CDataWithExteriorTrivia(testHost As TestHost) As Task Dim code = "'''<summary> '''<![CDATA[first '''second]]> '''</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first" & vbCrLf), XmlDoc.Delimiter("'''"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction1(testHost As TestHost) As Task Await TestAsync("''' <?", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction2(testHost As TestHost) As Task Await TestAsync("''' <??>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction3(testHost As TestHost) As Task Await TestAsync("''' <?xml", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("xml")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction4(testHost As TestHost) As Task Await TestAsync("''' <?xml version=""1.0""?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("xml"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("version=""1.0"""), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction5(testHost As TestHost) As Task Await TestAsync("''' <?goo?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction6(testHost As TestHost) As Task Await TestAsync("''' <?goo bar?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("bar"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestIsTrue(testHost As TestHost) As Task Await TestInClassAsync(" Public Shared Operator IsTrue(c As C) As Boolean", testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("IsTrue"), Punctuation.OpenParen, Parameter("c"), Keyword("As"), Identifier("C"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean")) End Function <Theory, CombinatorialData> Public Async Function TestIsFalse(testHost As TestHost) As Task Await TestInClassAsync(" Public Shared Operator IsFalse(c As C) As Boolean", testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("IsFalse"), Punctuation.OpenParen, Parameter("c"), Keyword("As"), Identifier("C"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean")) End Function <Theory, CombinatorialData> Public Async Function TestDelegate1(testHost As TestHost) As Task Await TestAsync("Delegate Sub Goo()", testHost, Keyword("Delegate"), Keyword("Sub"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestImports1(testHost As TestHost) As Task Dim code = "Imports Goo Imports Bar" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("Goo"), Keyword("Imports"), Identifier("Bar")) End Function ''' <summary> ''' Clear Syntax Error ''' </summary> <Theory, CombinatorialData> Public Async Function TestImports2(testHost As TestHost) As Task Dim code = "Imports Imports Bar" Await TestAsync(code, testHost, Keyword("Imports"), Keyword("Imports"), Identifier("Bar")) End Function <Theory, CombinatorialData> Public Async Function TestImports3(testHost As TestHost) As Task Dim code = "Imports Goo=Baz Imports Bar=Quux" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("Goo"), Operators.Equals, Identifier("Baz"), Keyword("Imports"), Identifier("Bar"), Operators.Equals, Identifier("Quux")) End Function <Theory, CombinatorialData> Public Async Function TestImports4(testHost As TestHost) As Task Dim code = "Imports System.Text" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("System"), Operators.Dot, Identifier("Text")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function '''<summary> ''' Broken XmlElement should classify ''' </summary> <Theory, CombinatorialData> Public Async Function TestXmlElement3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function '''<summary> ''' Broken end only element should still classify ''' </summary> <Theory, CombinatorialData> Public Async Function TestXmlElement4(testHost As TestHost) As Task Await TestInExpressionAsync("</goo>", testHost, VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar></goo.bar>", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo.bar"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:bar>hello</goo:bar>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo><%= bar %></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded3(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %>/>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>=""42""/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("42"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo a1=<%= bar %>/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("a1"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment1(testHost As TestHost) As Task Await TestInExpressionAsync("<!---->", testHost, VBXmlDelimiter("<!--"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment2(testHost As TestHost) As Task Await TestInExpressionAsync("<!--goo-->", testHost, VBXmlDelimiter("<!--"), VBXmlComment("goo"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment3(testHost As TestHost) As Task Await TestInExpressionAsync("<a><!--goo--></a>", testHost, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment("goo"), VBXmlDelimiter("-->"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlPreprocessingInstruction2(testHost As TestHost) As Task Await TestInExpressionAsync("<a><?pi value=2?></a>", testHost, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("<?"), VBXmlName("pi"), VBXmlProcessingInstruction("value=2"), VBXmlDelimiter("?>"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDescendantsMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x...<goo>", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("."), VBXmlDelimiter("."), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x.<goo>", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x.@goo", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("goo")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeMemberAccess2(testHost As TestHost) As Task Await TestInExpressionAsync("x.@goo:bar", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("goo"), VBXmlAttributeName(":"), VBXmlAttributeName("bar")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorReference(testHost As TestHost) As Task Await TestInNamespaceAsync("#R ""Ref""", testHost, PPKeyword("#"), PPKeyword("R"), [String]("""Ref""")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorConst1(testHost As TestHost) As Task Await TestInNamespaceAsync("#Const Goo = 1", testHost, PPKeyword("#"), PPKeyword("Const"), Identifier("Goo"), Operators.Equals, Number("1")) End Function Public Async Function TestPreprocessorConst2(testHost As TestHost) As Task Await TestInNamespaceAsync("#Const DebugCode = True", testHost, PPKeyword("#"), PPKeyword("Const"), Identifier("DebugCode"), Operators.Equals, Keyword("True")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorIfThen1(testHost As TestHost) As Task Await TestInNamespaceAsync("#If Goo Then", testHost, PPKeyword("#"), PPKeyword("If"), Identifier("Goo"), PPKeyword("Then")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorElseIf1(testHost As TestHost) As Task Await TestInNamespaceAsync("#ElseIf Goo Then", testHost, PPKeyword("#"), PPKeyword("ElseIf"), Identifier("Goo"), PPKeyword("Then")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorElse1(testHost As TestHost) As Task Await TestInNamespaceAsync("#Else", testHost, PPKeyword("#"), PPKeyword("Else")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorEndIf1(testHost As TestHost) As Task Await TestInNamespaceAsync("#End If", testHost, PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalSource1(testHost As TestHost) As Task Await TestInNamespaceAsync("#ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30)", testHost, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum1(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ""{12345678-1234-1234-1234-123456789abc}"", _ ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"")" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ' Test ""{12345678-1234-1234-1234-123456789abc}"", _ ' Test ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"")" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, Comment("' Test"), [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, Comment("' Test"), [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum2(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ""{12345678-1234-1234-1234-123456789abc}"", _ ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"") Module Test Sub Main() #ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30) Console.WriteLine(""In test.aspx"") #End ExternalSource End Sub End Module" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen, Keyword("Module"), [Module]("Test"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, [String]("""In test.aspx"""), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum2CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ' Test 1 ""{12345678-1234-1234-1234-123456789abc}"", _ ' Test 2 ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"") Module Test Sub Main() #ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30) Console.WriteLine(""In test.aspx"") #End ExternalSource End Sub End Module" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, Comment("' Test 1"), [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, Comment("' Test 2"), [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen, Keyword("Module"), [Module]("Test"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, [String]("""In test.aspx"""), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_1(testHost As TestHost) As Task Dim code = "Class PreprocessorNoContext Dim Region Dim ExternalSource End Class #Region ""Test"" #End Region #Region ""Test"" ' comment #End Region ' comment #Region ""Test"" REM comment #End Region REM comment # _ Region ""Test"" # _ End Region # _ Region _ ""Test"" # _ End _ Region" Await TestAsync(code, testHost, Keyword("Class"), [Class]("PreprocessorNoContext"), Keyword("Dim"), Field("Region"), Keyword("Dim"), Field("ExternalSource"), Keyword("End"), Keyword("Class"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' comment"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("REM comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("REM comment"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), LineContinuation, [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Class PreprocessorNoContext Dim Region Dim ExternalSource End Class #Region ""Test"" #End Region #Region ""Test"" ' comment #End Region ' comment #Region ""Test"" REM comment #End Region REM comment # _ ' Test 1 Region ""Test"" # _ ' Test 2 End Region # _ ' Test 3 Region _ ' Test 4 ""Test"" # _ ' Test 5 End _ ' Test 6 Region" Await TestAsync(code, testHost, Keyword("Class"), [Class]("PreprocessorNoContext"), Keyword("Dim"), Field("Region"), Keyword("Dim"), Field("ExternalSource"), Keyword("End"), Keyword("Class"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' comment"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("REM comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("REM comment"), PPKeyword("#"), LineContinuation, Comment("' Test 1"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, Comment("' Test 2"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, Comment("' Test 3"), PPKeyword("Region"), LineContinuation, Comment("' Test 4"), [String]("""Test"""), PPKeyword("#"), LineContinuation, Comment("' Test 5"), PPKeyword("End"), LineContinuation, Comment("' Test 6"), PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_2(testHost As TestHost) As Task Dim code = "#ExternalSource(""Test.vb"", 123) #End ExternalSource #ExternalSource(""Test.vb"", 123) ' comment #End ExternalSource REM comment # _ ExternalSource _ ( _ ""Test.vb"" _ , _ 123) # _ End _ ExternalSource" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""Test.vb"""), Punctuation.Comma, Number("123"), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""Test.vb"""), Punctuation.Comma, Number("123"), Punctuation.CloseParen, Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Comment("REM comment"), PPKeyword("#"), LineContinuation, PPKeyword("ExternalSource"), LineContinuation, Punctuation.OpenParen, LineContinuation, [String]("""Test.vb"""), LineContinuation, Punctuation.Comma, LineContinuation, Number("123"), Punctuation.CloseParen, PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("ExternalSource")) End Function <Theory, CombinatorialData> Public Async Function TestBug2640(testHost As TestHost) As Task Dim code = "# _ Region ""Test"" # _ End Region # _ Region _ ""Test"" # _ End _ Region" Await TestAsync(code, testHost, PPKeyword("#"), LineContinuation, PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), LineContinuation, [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2638(testHost As TestHost) As Task Dim code = "Module M Sub Main() Dim dt = #1/1/2000# End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("M"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("dt"), Operators.Equals, Number("#1/1/2000#"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug2562(testHost As TestHost) As Task Dim code = "Module Program Sub Main(args As String()) #region ""Goo"" #End region REM dfkjslfkdsjf End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Parameter("args"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("region"), [String]("""Goo"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("region"), Comment("REM dfkjslfkdsjf"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug3004(testHost As TestHost) As Task Dim code = "''' <summary> ''' &#65; ''' </summary> Module M End Module" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Module"), [Module]("M"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug3006(testHost As TestHost) As Task Dim code = "#If True Then ' comment #End If" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("If"), Keyword("True"), PPKeyword("Then"), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestBug3008(testHost As TestHost) As Task Dim code = "#If #12/2/2010# = #12/2/2010# Then #End If" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("If"), Number("#12/2/2010#"), Operators.Equals, Number("#12/2/2010#"), PPKeyword("Then"), PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestBug927678(testHost As TestHost) As Task Dim code = "'This is not usually a " & vbCrLf & "'collapsible comment block" & vbCrLf & "x = 2" Await TestInMethodAsync(code, testHost, Comment("'This is not usually a "), Comment("'collapsible comment block"), Identifier("x"), Operators.Equals, Number("2")) End Function <Theory, CombinatorialData> Public Async Function TestAttribute(testHost As TestHost) As Task Dim code = "<Assembly: Goo()>" Await TestAsync(code, testHost, Punctuation.OpenAngle, Keyword("Assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseAngle) End Function <Theory, CombinatorialData> Public Async Function TestAngleBracketsOnGenericConstraints_Bug932262(testHost As TestHost) As Task Dim code = "Class C(Of T As A(Of T)) End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C"), Punctuation.OpenParen, Keyword("Of"), TypeParameter("T"), Keyword("As"), Identifier("A"), Punctuation.OpenParen, Keyword("Of"), Identifier("T"), Punctuation.CloseParen, Punctuation.CloseParen, Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestIntegerAsContextualKeyword(testHost As TestHost) As Task Dim code = "Sub CallMeInteger(ByVal [Integer] As Integer) CallMeInteger(Integer:=1) CallMeInteger(Integer _ := _ 1) End Sub Dim [Class] As Integer" Await TestInClassAsync(code, testHost, Keyword("Sub"), Method("CallMeInteger"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("[Integer]"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), LineContinuation, Operators.ColonEquals, LineContinuation, Number("1"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("Dim"), Field("[Class]"), Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestIntegerAsContextualKeywordCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Sub CallMeInteger(ByVal [Integer] As Integer) CallMeInteger(Integer:=1) CallMeInteger(Integer _ ' Test 1 := _ ' Test 2 1) End Sub Dim [Class] As Integer" Await TestInClassAsync(code, testHost, Keyword("Sub"), Method("CallMeInteger"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("[Integer]"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), LineContinuation, Comment("' Test 1"), Operators.ColonEquals, LineContinuation, Comment("' Test 2"), Number("1"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("Dim"), Field("[Class]"), Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestIndexStrings(testHost As TestHost) As Task Dim code = "Default ReadOnly Property IndexMe(ByVal arg As String) As Integer Get With Me Dim t = !String t = ! _ String t = .Class t = . _ Class End With End Get End Property" Await TestAsync(code, testHost, Keyword("Default"), Keyword("ReadOnly"), Keyword("Property"), [Property]("IndexMe"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("arg"), Keyword("As"), Keyword("String"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), Keyword("Get"), Keyword("With"), Keyword("Me"), Keyword("Dim"), Local("t"), Operators.Equals, Operators.Exclamation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Exclamation, LineContinuation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Dot, Identifier("Class"), Identifier("t"), Operators.Equals, Operators.Dot, LineContinuation, Identifier("Class"), Keyword("End"), Keyword("With"), Keyword("End"), Keyword("Get"), Keyword("End"), Keyword("Property")) End Function <Theory, CombinatorialData> Public Async Function TestIndexStringsCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Default ReadOnly Property IndexMe(ByVal arg As String) As Integer Get With Me Dim t = !String t = ! _ ' Test 1 String t = .Class t = . _ ' Test 2 Class End With End Get End Property" Await TestAsync(code, testHost, Keyword("Default"), Keyword("ReadOnly"), Keyword("Property"), [Property]("IndexMe"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("arg"), Keyword("As"), Keyword("String"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), Keyword("Get"), Keyword("With"), Keyword("Me"), Keyword("Dim"), Local("t"), Operators.Equals, Operators.Exclamation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Exclamation, LineContinuation, Comment("' Test 1"), Identifier("String"), Identifier("t"), Operators.Equals, Operators.Dot, Identifier("Class"), Identifier("t"), Operators.Equals, Operators.Dot, LineContinuation, Comment("' Test 2"), Identifier("Class"), Keyword("End"), Keyword("With"), Keyword("End"), Keyword("Get"), Keyword("End"), Keyword("Property")) End Function <Theory, CombinatorialData> Public Async Function TestMyIsIdentifierOnSyntaxLevel(testHost As TestHost) As Task Dim code = "Dim My Dim var = My.Application.GetEnvironmentVariable(""test"") Sub CallMeMy(ByVal My As Integer) CallMeMy(My:=1) CallMeMy(My _ := _ 1) My.ToString() With Me .My = 1 . _ My _ = 1 !My = Nothing ! _ My _ = Nothing End With Me.My.ToString() Me. _ My.ToString() Me.My = 1 Me. _ My = 1 End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("My"), Keyword("Dim"), Field("var"), Operators.Equals, Identifier("My"), Operators.Dot, Identifier("Application"), Operators.Dot, Identifier("GetEnvironmentVariable"), Punctuation.OpenParen, [String]("""test"""), Punctuation.CloseParen, Keyword("Sub"), Method("CallMeMy"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("My"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), LineContinuation, Operators.ColonEquals, LineContinuation, Number("1"), Punctuation.CloseParen, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Operators.Dot, LineContinuation, Identifier("My"), LineContinuation, Operators.Equals, Number("1"), Operators.Exclamation, Identifier("My"), Operators.Equals, Keyword("Nothing"), Operators.Exclamation, LineContinuation, Identifier("My"), LineContinuation, Operators.Equals, Keyword("Nothing"), Keyword("End"), Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, LineContinuation, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Keyword("Me"), Operators.Dot, LineContinuation, Identifier("My"), Operators.Equals, Number("1"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestMyIsIdentifierOnSyntaxLevelCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim My Dim var = My.Application.GetEnvironmentVariable(""test"") Sub CallMeMy(ByVal My As Integer) CallMeMy(My:=1) CallMeMy(My _ ' Test 1 := _ ' Test 2 1) My.ToString() With Me .My = 1 . _ ' Test 3 My _ ' Test 4 = 1 !My = Nothing ! _ ' Test 5 My _ ' Test 6 = Nothing End With Me.My.ToString() Me. _ ' Test 7 My.ToString() Me.My = 1 Me. _ ' Test 8 My = 1 End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("My"), Keyword("Dim"), Field("var"), Operators.Equals, Identifier("My"), Operators.Dot, Identifier("Application"), Operators.Dot, Identifier("GetEnvironmentVariable"), Punctuation.OpenParen, [String]("""test"""), Punctuation.CloseParen, Keyword("Sub"), Method("CallMeMy"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("My"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), LineContinuation, Comment("' Test 1"), Operators.ColonEquals, LineContinuation, Comment("' Test 2"), Number("1"), Punctuation.CloseParen, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Operators.Dot, LineContinuation, Comment("' Test 3"), Identifier("My"), LineContinuation, Comment("' Test 4"), Operators.Equals, Number("1"), Operators.Exclamation, Identifier("My"), Operators.Equals, Keyword("Nothing"), Operators.Exclamation, LineContinuation, Comment("' Test 5"), Identifier("My"), LineContinuation, Comment("' Test 6"), Operators.Equals, Keyword("Nothing"), Keyword("End"), Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, LineContinuation, Comment("' Test 7"), Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Keyword("Me"), Operators.Dot, LineContinuation, Comment("' Test 8"), Identifier("My"), Operators.Equals, Number("1"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestIsTrueIsFalse(testHost As TestHost) As Task Dim code = "Class IsTrueIsFalseTests Dim IsTrue Dim IsFalse Shared Operator IsTrue(ByVal x As IsTrueIsFalseTests) As Boolean End Operator Shared Operator IsFalse(ByVal x As IsTrueIsFalseTests) As Boolean End Operator End Class" Await TestInClassAsync(code, testHost, Keyword("Class"), [Class]("IsTrueIsFalseTests"), Keyword("Dim"), Field("IsTrue"), Keyword("Dim"), Field("IsFalse"), Keyword("Shared"), Keyword("Operator"), Keyword("IsTrue"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("x"), Keyword("As"), Identifier("IsTrueIsFalseTests"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean"), Keyword("End"), Keyword("Operator"), Keyword("Shared"), Keyword("Operator"), Keyword("IsFalse"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("x"), Keyword("As"), Identifier("IsTrueIsFalseTests"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean"), Keyword("End"), Keyword("Operator"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestDeclareAnsiAutoUnicode(testHost As TestHost) As Task Dim code = " Dim Ansi Dim Unicode Dim Auto Declare Ansi Sub AnsiTest Lib ""Test.dll"" () Declare Auto Sub AutoTest Lib ""Test.dll"" () Declare Unicode Sub UnicodeTest Lib ""Test.dll"" () Declare _ Ansi Sub AnsiTest2 Lib ""Test.dll"" () Declare _ Auto Sub AutoTest2 Lib ""Test.dll"" () Declare _ Unicode Sub UnicodeTest2 Lib ""Test.dll"" ()" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Ansi"), Keyword("Dim"), Field("Unicode"), Keyword("Dim"), Field("Auto"), Keyword("Declare"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Auto"), Keyword("Sub"), Method("AutoTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestDeclareAnsiAutoUnicodeCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Ansi Dim Unicode Dim Auto Declare Ansi Sub AnsiTest Lib ""Test.dll"" () Declare Auto Sub AutoTest Lib ""Test.dll"" () Declare Unicode Sub UnicodeTest Lib ""Test.dll"" () Declare _ ' Test 1 Ansi Sub AnsiTest2 Lib ""Test.dll"" () Declare _ ' Test 2 Auto Sub AutoTest2 Lib ""Test.dll"" () Declare _ ' Test 3 Unicode Sub UnicodeTest2 Lib ""Test.dll"" ()" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Ansi"), Keyword("Dim"), Field("Unicode"), Keyword("Dim"), Field("Auto"), Keyword("Declare"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 1"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 2"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 3"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestUntil(testHost As TestHost) As Task Dim code = " Dim Until Sub TestSub() Do Loop Until True Do Loop _ Until True Do Until True Loop Do _ Until True Loop End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Until"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, ControlKeyword("Do"), ControlKeyword("Loop"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Loop"), LineContinuation, ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), ControlKeyword("Do"), LineContinuation, ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestUntilCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Until Sub TestSub() Do Loop Until True Do Loop _ ' Test 1 Until True Do Until True Loop Do _ ' Test 2 Until True Loop End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Until"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, ControlKeyword("Do"), ControlKeyword("Loop"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Loop"), LineContinuation, Comment("' Test 1"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), ControlKeyword("Do"), LineContinuation, Comment("' Test 2"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestPreserve(testHost As TestHost) As Task Dim code = " Dim Preserve Sub TestSub() Dim arr As Integer() = Nothing ReDim Preserve arr(0) ReDim _ Preserve arr(0) End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Preserve"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("arr"), Keyword("As"), Keyword("Integer"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Keyword("Nothing"), Keyword("ReDim"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("ReDim"), LineContinuation, Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestPreserveCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Preserve Sub TestSub() Dim arr As Integer() = Nothing ReDim Preserve arr(0) ReDim _ ' Test Preserve arr(0) End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Preserve"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("arr"), Keyword("As"), Keyword("Integer"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Keyword("Nothing"), Keyword("ReDim"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("ReDim"), LineContinuation, Comment("' Test"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestSkippedTextAsTokens(testHost As TestHost) As Task Dim code = "Module Program Sub Test(ByVal readOnly As Boolean) End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Test"), Punctuation.OpenParen, Keyword("ByVal"), Keyword("readOnly"), Parameter("As"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(538647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538647")> Public Async Function TestRegression4315_VariableNamesClassifiedAsType(testHost As TestHost) As Task Dim code = "Module M Sub S() Dim goo End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("M"), Keyword("Sub"), Method("S"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("goo"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(539203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539203")> Public Async Function TestColonTrivia(testHost As TestHost) As Task Await TestInMethodAsync(" : Console.WriteLine()", testHost, Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> <WorkItem(539642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539642")> Public Async Function TestFromInCollectionInitializer1(testHost As TestHost) As Task Await TestInMethodAsync("Dim y = New Goo() From", testHost, Keyword("Dim"), Local("y"), Operators.Equals, Keyword("New"), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("From")) End Function <Theory, CombinatorialData> <WorkItem(539642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539642")> Public Async Function TestFromInCollectionInitializer2(testHost As TestHost) As Task Await TestInMethodAsync("Dim y As New Goo() From", testHost, Keyword("Dim"), Local("y"), Keyword("As"), Keyword("New"), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("From")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport1(testHost As TestHost) As Task Await TestAsync("Imports <x", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlName("x")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport2(testHost As TestHost) As Task Await TestAsync("Imports <xml", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlName("xml")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport3(testHost As TestHost) As Task Await TestAsync("Imports <xmlns", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport4(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport5(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport6(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("=")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport7(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=""http://goo""", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("http://goo"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestFullyTypedXmlNamespaceImport(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=""http://goo"">", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("http://goo"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestGetXmlNamespaceExpression(testHost As TestHost) As Task Await TestInExpressionAsync("GetXmlNamespace(Name)", testHost, Keyword("GetXmlNamespace"), Punctuation.OpenParen, VBXmlName("Name"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestGetXmlNamespaceExpressionWithNoName(testHost As TestHost) As Task Await TestInExpressionAsync("GetXmlNamespace()", testHost, Keyword("GetXmlNamespace"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestClassifyXmlDocumentFollowingMisc(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml ?><x></x><!--h-->", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("x"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("x"), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment("h"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDeclaration(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml version=""1.0""?>", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>")) End Function <Theory, CombinatorialData> Public Async Function TestEnableWarningDirective(testHost As TestHost) As Task Dim code = "Module Program Sub Main #Enable Warning BC123, [bc456], SomeId End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), PPKeyword("Enable"), PPKeyword("Warning"), Identifier("BC123"), Punctuation.Comma, Identifier("[bc456]"), Punctuation.Comma, Identifier("SomeId"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestDisableWarningDirective(testHost As TestHost) As Task Dim code = "Module Program Sub Main #Disable Warning End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), PPKeyword("Disable"), PPKeyword("Warning"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBadWarningDirectives(testHost As TestHost) As Task Dim code = "Module Program Sub Main #warning End Sub #Enable blah Warning End Module #Disable bc123 Warning #Enable #Disable Warning blah" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), Identifier("warning"), Keyword("End"), Keyword("Sub"), PPKeyword("#"), PPKeyword("Enable"), Identifier("blah"), Identifier("Warning"), Keyword("End"), Keyword("Module"), PPKeyword("#"), PPKeyword("Disable"), Identifier("bc123"), Identifier("Warning"), PPKeyword("#"), PPKeyword("Enable"), PPKeyword("#"), PPKeyword("Disable"), PPKeyword("Warning"), Identifier("blah")) End Function <Theory, CombinatorialData> Public Async Function TestInterpolatedString1(testHost As TestHost) As Task Dim code = "Module Program Sub Main Dim s = $""Hello, {name,10:F}."" End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Keyword("Dim"), Local("s"), Operators.Equals, [String]("$"""), [String]("Hello, "), Punctuation.OpenCurly, Identifier("name"), Punctuation.Comma, Number("10"), Punctuation.Colon, [String]("F"), Punctuation.CloseCurly, [String]("."), [String](""""), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestInterpolatedString2(testHost As TestHost) As Task Dim code = "Module Program Sub Main Dim s = $""{x}, {y}"" End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Keyword("Dim"), Local("s"), Operators.Equals, [String]("$"""), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, [String](", "), Punctuation.OpenCurly, Identifier("y"), Punctuation.CloseCurly, [String](""""), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(2126, "https://github.com/dotnet/roslyn/issues/2126")> Public Async Function CommentBeforeXmlAccessExpression(testHost As TestHost) As Task Dim code = " ' Comment x.@Name = ""Text"" ' Comment" Await TestInMethodAsync( className:="C", methodName:="M", code, testHost, Comment("' Comment"), Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("Name"), Operators.Equals, [String]("""Text"""), Comment("' Comment")) End Function <Theory, CombinatorialData> <WorkItem(3291, "https://github.com/dotnet/roslyn/issues/3291")> Public Async Function TestCommentOnCollapsedEndRegion(testHost As TestHost) As Task Dim code = "#Region ""Stuff"" #End Region ' Stuff" Await TestAsync( code, testHost, PPKeyword("#"), PPKeyword("Region"), [String]("""Stuff"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' Stuff")) End Function <Theory, CombinatorialData> Public Async Function TestConflictMarkers1(testHost As TestHost) As Task Dim code = "interface I <<<<<<< Start sub Goo() ======= sub Bar() >>>>>>> End end interface" Await TestAsync( code, testHost, Keyword("interface"), [Interface]("I"), Comment("<<<<<<< Start"), Keyword("sub"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Comment("======="), Keyword("sub"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Comment(">>>>>>> End"), Keyword("end"), Keyword("interface")) End Function <Theory, CombinatorialData> Public Async Function TestConstField(testHost As TestHost) As Task Dim code = "Const Number = 42" Await TestInClassAsync(code, testHost, Keyword("Const"), Constant("Number"), [Static]("Number"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestLocalConst(testHost As TestHost) As Task Dim code = "Const Number = 42" Await TestInMethodAsync(code, testHost, Keyword("Const"), Constant("Number"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInLocals(testHost As TestHost) As Task Dim code = "Dim x$ = ""23"" x$ = ""19""" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("x$"), Operators.Equals, [String]("""23"""), Identifier("x$"), Operators.Equals, [String]("""19""")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInFields(testHost As TestHost) As Task Dim code = "Const x$ = ""23"" Dim y$ = x$" Await TestInClassAsync(code, testHost, Keyword("Const"), Constant("x$"), [Static]("x$"), Operators.Equals, [String]("""23"""), Keyword("Dim"), Field("y$"), Operators.Equals, Identifier("x$")) End Function <Theory, CombinatorialData> Public Async Function TestFunctionNamesWithTypeCharacters(testHost As TestHost) As Task Dim code = "Function x%() x% = 42 End Function" Await TestInClassAsync(code, testHost, Keyword("Function"), Method("x%"), Punctuation.OpenParen, Punctuation.CloseParen, Identifier("x%"), Operators.Equals, Number("42"), Keyword("End"), Keyword("Function")) End Function <Theory, CombinatorialData> Public Async Function TestExtensionMethod(testHost As TestHost) As Task Dim code = " Imports System.Runtime.CompilerServices Module M <Extension> Sub Square(ByRef x As Integer) x = x * x End Sub End Module Class C Sub Test() Dim x = 42 x.Square() M.Square(x) End Sub End Class" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("System"), Operators.Dot, Identifier("Runtime"), Operators.Dot, Identifier("CompilerServices"), Keyword("Module"), [Module]("M"), Punctuation.OpenAngle, Identifier("Extension"), Punctuation.CloseAngle, Keyword("Sub"), Method("Square"), Punctuation.OpenParen, Keyword("ByRef"), Parameter("x"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("x"), Operators.Equals, Identifier("x"), Operators.Asterisk, Identifier("x"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module"), Keyword("Class"), [Class]("C"), Keyword("Sub"), Method("Test"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("x"), Operators.Equals, Number("42"), Identifier("x"), Operators.Dot, Identifier("Square"), Punctuation.OpenParen, Punctuation.CloseParen, Identifier("M"), Operators.Dot, Identifier("Square"), Punctuation.OpenParen, Identifier("x"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestSimpleEvent(testHost As TestHost) As Task Dim code = " Event E(x As Integer) Sub M() RaiseEvent E(42) End Sub" Await TestInClassAsync(code, testHost, Keyword("Event"), [Event]("E"), Punctuation.OpenParen, Parameter("x"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Keyword("Sub"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("RaiseEvent"), Identifier("E"), Punctuation.OpenParen, Number("42"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestOperators(testHost As TestHost) As Task Dim code = " Public Shared Operator Not(t As Test) As Test Return New Test() End Operator Public Shared Operator +(t1 As Test, t2 As Test) As Integer Return 1 End Operator" Await TestInClassAsync(code, testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("Not"), Punctuation.OpenParen, Parameter("t"), Keyword("As"), Identifier("Test"), Punctuation.CloseParen, Keyword("As"), Identifier("Test"), ControlKeyword("Return"), Keyword("New"), Identifier("Test"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("End"), Keyword("Operator"), Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Operators.Plus, Punctuation.OpenParen, Parameter("t1"), Keyword("As"), Identifier("Test"), Punctuation.Comma, Parameter("t2"), Keyword("As"), Identifier("Test"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), ControlKeyword("Return"), Number("1"), Keyword("End"), Keyword("Operator")) End Function <Theory, CombinatorialData> Public Async Function TestLabelName(testHost As TestHost) As Task Dim code = "Sub Main E: GoTo E End Sub" Await TestAsync(code, testHost, Keyword("Sub"), Method("Main"), Label("E"), Punctuation.Colon, ControlKeyword("GoTo"), Identifier("E"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestCatchStatement(testHost As TestHost) As Task Dim code = "Try Catch ex As Exception End Try" Await TestInMethodAsync(code, testHost, ControlKeyword("Try"), ControlKeyword("Catch"), Local("ex"), Keyword("As"), Identifier("Exception"), ControlKeyword("End"), ControlKeyword("Try")) 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.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Classification <Trait(Traits.Feature, Traits.Features.Classification)> Public Class SyntacticClassifierTests Inherits AbstractVisualBasicClassifierTests Protected Overrides Async Function GetClassificationSpansAsync(code As String, span As TextSpan, parseOptions As ParseOptions, testHost As TestHost) As Task(Of ImmutableArray(Of ClassifiedSpan)) Using workspace = CreateWorkspace(code, testHost) Dim document = workspace.CurrentSolution.Projects.First().Documents.First() Return Await GetSyntacticClassificationsAsync(document, span) End Using End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo", testHost, VBXmlDelimiter("<"), VBXmlName("goo")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.", testHost, VBXmlDelimiter("<"), VBXmlName("goo.")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.b", testHost, VBXmlDelimiter("<"), VBXmlName("goo.b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.b>", testHost, VBXmlDelimiter("<"), VBXmlName("goo.b"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName8(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlStartElementName9(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:b>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("b"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo. />", testHost, VBXmlDelimiter("<"), VBXmlName("goo."), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo: />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmptyElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("b")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo ba", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("ba")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeName3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("=")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""b", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("b" & vbCrLf)) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba" & vbCrLf)) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""b""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("b"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValue7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba""", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValueMultiple1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba"" baz="""" ", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("baz"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeValueMultiple2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=""ba"" baz=""a"" ", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("ba"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("baz"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("a"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent1(testHost As TestHost) As Task Await TestInExpressionAsync("<f>&l</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEntityReference("&"), VBXmlText("l"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent2(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent3(testHost As TestHost) As Task Await TestInExpressionAsync("<f>&#x03C0;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEntityReference("&#x03C0;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent4(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &#x03C0;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&#x03C0;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent5(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt;</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent6(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt; bar</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;"), VBXmlText(" bar"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementContent7(testHost As TestHost) As Task Await TestInExpressionAsync("<f>goo &lt;", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlText("goo "), VBXmlEntityReference("&lt;")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData1(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[bar]]></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("bar"), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData4(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[bar]]>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("bar"), VBXmlDelimiter("]]>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData5(testHost As TestHost) As Task Await TestInExpressionAsync("<f><![CDATA[<>/]]>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("<>/"), VBXmlDelimiter("]]>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlCData6(testHost As TestHost) As Task Dim code = "<f><![CDATA[goo baz]]></f>" Await TestInExpressionAsync(code, testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("goo" & vbCrLf), VBXmlCDataSection("baz"), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName1(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= ", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%=")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName2(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName3(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName4(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar.Baz() %>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Baz"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName5(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar.Baz() %> />", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Baz"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAtElementName6(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %> />", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttribute4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %> />", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), Operators.GreaterThan) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue2(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz %> >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsAttributeValue3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo bar=<%=baz.Goo %> >", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("bar"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("baz"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent1(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar %></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent2(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar.Goo %></f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContent3(testHost As TestHost) As Task Await TestInExpressionAsync("<f><%= bar.Goo %> jaz</f>", testHost, VBXmlDelimiter("<"), VBXmlName("f"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), Operators.Dot, Identifier("Goo"), VBXmlEmbeddedExpression("%>"), VBXmlText(" jaz"), VBXmlDelimiter("</"), VBXmlName("f"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContentNested(testHost As TestHost) As Task Dim code = "Dim doc = _ <goo> <%= <bug141> <a>hello</a> </bug141> %> </goo>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("doc"), Operators.Equals, LineContinuation, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), VBXmlDelimiter("<"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbeddedExpressionAsElementContentNestedCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim doc = _ ' Test <goo> <%= <bug141> <a>hello</a> </bug141> %> </goo>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("doc"), Operators.Equals, LineContinuation, Comment("' Test"), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), VBXmlDelimiter("<"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("bug141"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiteralsInLambdas(testHost As TestHost) As Task Dim code = "Dim x = Function() _ <element val=""something""/> Dim y = Function() <element val=""something""/>" Await TestAsync(code, testHost, Keyword("Dim"), Field("x"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), Keyword("Dim"), Field("y"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiteralsInLambdasCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim x = Function() _ 'Test <element val=""something""/> Dim y = Function() <element val=""something""/>" Await TestAsync(code, testHost, Keyword("Dim"), Field("x"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Comment("'Test"), VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), Keyword("Dim"), Field("y"), Operators.Equals, Keyword("Function"), Punctuation.OpenParen, Punctuation.CloseParen, VBXmlDelimiter("<"), VBXmlName("element"), VBXmlAttributeName("val"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("something"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocumentPrologue(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("encoding"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("UTF-8"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("standalone"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("yes"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals1(testHost As TestHost) As Task Dim code = "Dim a = <Customer id1=""1"" id2=""2"" id3=<%= n2 %> id4=""""> <!-- This is a simple Xml element with all of the node types --> <Name>Me</Name> <NameUsingExpression><%= n1 %></NameUsingExpression> <Street>10802 177th CT NE</Street> <Misc><![CDATA[Let's add some CDATA for fun. ]]> </Misc> <Empty><%= Nothing %></Empty> </Customer>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("a"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("id1"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id2"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id3"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("n2"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("id4"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment(" This is a simple Xml element with all of the node types "), VBXmlDelimiter("-->"), VBXmlDelimiter("<"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlText("Me"), VBXmlDelimiter("</"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("n1"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlText("10802 177th CT NE"), VBXmlDelimiter("</"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("Let's add some CDATA" & Environment.NewLine), VBXmlCDataSection(" for fun. "), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Keyword("Nothing"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals2(testHost As TestHost) As Task Dim code = "Dim b = <?xml version=""1.0""?> <!-- comment before the root --> <?my-PI PI before the root ?> <p:Customer id1=""1"" id2=""2"" id3=<%= n2 %> id4=""""> <!-- This is a simple Xml element with all of the node types --> <q:Name>Me</q:Name> <s:NameUsingExpression><%= n1 %></s:NameUsingExpression> <t:Street>10802 177th CT NE</t:Street> <p:Misc><![CDATA[Let's add some CDATA for fun. ]]> </p:Misc> <Empty><%= Nothing %></Empty> <entity>hello&#x7b;world</entity> </p:Customer>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("b"), Operators.Equals, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<!--"), VBXmlComment(" comment before the root "), VBXmlDelimiter("-->"), VBXmlDelimiter("<?"), VBXmlName("my-PI"), VBXmlProcessingInstruction("PI before the root "), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Customer"), VBXmlAttributeName("id1"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id2"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("id3"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("n2"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("id4"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment(" This is a simple Xml element with all of the node types "), VBXmlDelimiter("-->"), VBXmlDelimiter("<"), VBXmlName("q"), VBXmlName(":"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlText("Me"), VBXmlDelimiter("</"), VBXmlName("q"), VBXmlName(":"), VBXmlName("Name"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("s"), VBXmlName(":"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("n1"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("s"), VBXmlName(":"), VBXmlName("NameUsingExpression"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("t"), VBXmlName(":"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlText("10802 177th CT NE"), VBXmlDelimiter("</"), VBXmlName("t"), VBXmlName(":"), VBXmlName("Street"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<![CDATA["), VBXmlCDataSection("Let's add some CDATA for fun. "), VBXmlDelimiter("]]>"), VBXmlDelimiter("</"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Misc"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Keyword("Nothing"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("Empty"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("entity"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlEntityReference("&#x7b;"), VBXmlText("world"), VBXmlDelimiter("</"), VBXmlName("entity"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("p"), VBXmlName(":"), VBXmlName("Customer"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals3(testHost As TestHost) As Task Dim code = "Dim c = <p:x xmlns:p=""abc 123""/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("c"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("p"), VBXmlName(":"), VBXmlName("x"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("p"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("abc" & vbCrLf), VBXmlAttributeValue("123"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals4(testHost As TestHost) As Task Dim code = "Dim d = _ <?xml version=""1.0""?> <a/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("d"), Operators.Equals, LineContinuation, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals4CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim d = _ ' Test <?xml version=""1.0""?> <a/>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("d"), Operators.Equals, LineContinuation, Comment("' Test"), VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals5(testHost As TestHost) As Task Dim code = "Dim i = 100 Process( _ <Customer ID=<%= i + 1000 %> a=""""> </Customer>)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, Number("100"), Identifier("Process"), Punctuation.OpenParen, LineContinuation, VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("ID"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("i"), Operators.Plus, Number("1000"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("a"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals5CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim i = 100 Process( _ ' Test <Customer ID=<%= i + 1000 %> a=""""> </Customer>)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, Number("100"), Identifier("Process"), Punctuation.OpenParen, LineContinuation, Comment("' Test"), VBXmlDelimiter("<"), VBXmlName("Customer"), VBXmlAttributeName("ID"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("i"), Operators.Plus, Number("1000"), VBXmlEmbeddedExpression("%>"), VBXmlAttributeName("a"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("Customer"), VBXmlDelimiter(">"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals6(testHost As TestHost) As Task Dim code = "Dim xmlwithkeywords = <MODULE> <CLASS> <FUNCTION> <DIM i=""1""/> <FOR j=""1"" to=""i""> <NEXT/> </FOR> <END/> </FUNCTION> </CLASS> </MODULE>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("xmlwithkeywords"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("MODULE"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("CLASS"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("FUNCTION"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("DIM"), VBXmlAttributeName("i"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>"), VBXmlDelimiter("<"), VBXmlName("FOR"), VBXmlAttributeName("j"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("to"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("i"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("NEXT"), VBXmlDelimiter("/>"), VBXmlDelimiter("</"), VBXmlName("FOR"), VBXmlDelimiter(">"), VBXmlDelimiter("<"), VBXmlName("END"), VBXmlDelimiter("/>"), VBXmlDelimiter("</"), VBXmlName("FUNCTION"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("CLASS"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("MODULE"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlLiterals7(testHost As TestHost) As Task Dim code = "Dim spacetest = <a b=""1"" c=""2""> </a>" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("spacetest"), Operators.Equals, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlAttributeName("b"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1"), VBXmlAttributeQuotes(""""), VBXmlAttributeName("c"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("2"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestOptionKeywordsInClassContext(testHost As TestHost) As Task Dim code = "Class OptionNoContext Dim Infer Dim Explicit Dim Strict Dim Off Dim Compare Dim Text Dim Binary End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("OptionNoContext"), Keyword("Dim"), Field("Infer"), Keyword("Dim"), Field("Explicit"), Keyword("Dim"), Field("Strict"), Keyword("Dim"), Field("Off"), Keyword("Dim"), Field("Compare"), Keyword("Dim"), Field("Text"), Keyword("Dim"), Field("Binary"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestOptionInferAndExplicit(testHost As TestHost) As Task Dim text = "Option Infer On Option Explicit Off" Await TestAsync(text, testHost, Keyword("Option"), Keyword("Infer"), Keyword("On"), Keyword("Option"), Keyword("Explicit"), Keyword("Off")) End Function <Theory, CombinatorialData> Public Async Function TestOptionCompareTextBinary(testHost As TestHost) As Task Dim code = "Option Compare Text ' comment Option Compare Binary " Await TestAsync(code, testHost, Keyword("Option"), Keyword("Compare"), Keyword("Text"), Comment("' comment"), Keyword("Option"), Keyword("Compare"), Keyword("Binary")) End Function <Theory, CombinatorialData> Public Async Function TestOptionInfer1(testHost As TestHost) As Task Await TestAsync("Option Infer", testHost, Keyword("Option"), Keyword("Infer")) End Function <Theory, CombinatorialData> Public Async Function TestOptionExplicit1(testHost As TestHost) As Task Await TestAsync("Option Explicit", testHost, Keyword("Option"), Keyword("Explicit")) End Function <Theory, CombinatorialData> Public Async Function TestOptionStrict1(testHost As TestHost) As Task Await TestAsync("Option Strict", testHost, Keyword("Option"), Keyword("Strict")) End Function <Theory, CombinatorialData> Public Async Function TestLinqContextualKeywords(testHost As TestHost) As Task Dim code = "Dim from = 0 Dim aggregate = 0 Dim ascending = 0 Dim descending = 0 Dim distinct = 0 Dim by = 0 Shadows equals = 0 Dim group = 0 Dim into = 0 Dim join = 0 Dim skip = 0 Dim take = 0 Dim where = 0 Dim order = 0" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("from"), Operators.Equals, Number("0"), Keyword("Dim"), Field("aggregate"), Operators.Equals, Number("0"), Keyword("Dim"), Field("ascending"), Operators.Equals, Number("0"), Keyword("Dim"), Field("descending"), Operators.Equals, Number("0"), Keyword("Dim"), Field("distinct"), Operators.Equals, Number("0"), Keyword("Dim"), Field("by"), Operators.Equals, Number("0"), Keyword("Shadows"), Field("equals"), Operators.Equals, Number("0"), Keyword("Dim"), Field("group"), Operators.Equals, Number("0"), Keyword("Dim"), Field("into"), Operators.Equals, Number("0"), Keyword("Dim"), Field("join"), Operators.Equals, Number("0"), Keyword("Dim"), Field("skip"), Operators.Equals, Number("0"), Keyword("Dim"), Field("take"), Operators.Equals, Number("0"), Keyword("Dim"), Field("where"), Operators.Equals, Number("0"), Keyword("Dim"), Field("order"), Operators.Equals, Number("0")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression1(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goo", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goo")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression2(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goofooo.Goo", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goofooo"), Operators.Dot, Identifier("Goo")) End Function <Theory, CombinatorialData> Public Async Function TestFromLinqExpression3(testHost As TestHost) As Task Await TestInExpressionAsync("From it ", testHost, Keyword("From"), Identifier("it")) End Function <Theory, CombinatorialData> Public Async Function TestFromNotInContext1(testHost As TestHost) As Task Dim code = "Class From End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("From"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestFromNotInContext2(testHost As TestHost) As Task Await TestInMethodAsync("Dim from = 42", testHost, Keyword("Dim"), Local("from"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestWhereLinqExpression1(testHost As TestHost) As Task Await TestInExpressionAsync("From it in goo Where it <> 4", testHost, Keyword("From"), Identifier("it"), Keyword("in"), Identifier("goo"), Keyword("Where"), Identifier("it"), Operators.LessThanGreaterThan, Number("4")) End Function <Theory, CombinatorialData> Public Async Function TestLinqQuery1(testHost As TestHost) As Task Dim code = "Dim src = New List(Of Boolean) Dim var3 = 1 Dim q = From var1 In src Where var1 And True _ Order By var1 Ascending Order By var1 Descending _ Select var1 Distinct _ Join var2 In src On var1 Equals var2 _ Skip var3 Skip While var3 Take var3 Take While var3 _ Aggregate var4 In src _ Group var4 By var4 Into var5 = Count() _ Group Join var6 In src On var6 Equals var5 Into var7 Into var8 = Count()" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("src"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("Dim"), Local("var3"), Operators.Equals, Number("1"), Keyword("Dim"), Local("q"), Operators.Equals, Keyword("From"), Identifier("var1"), Keyword("In"), Identifier("src"), Keyword("Where"), Identifier("var1"), Keyword("And"), Keyword("True"), LineContinuation, Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Ascending"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Descending"), LineContinuation, Keyword("Select"), Identifier("var1"), Keyword("Distinct"), LineContinuation, Keyword("Join"), Identifier("var2"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var1"), Keyword("Equals"), Identifier("var2"), LineContinuation, Keyword("Skip"), Identifier("var3"), Keyword("Skip"), Keyword("While"), Identifier("var3"), Keyword("Take"), Identifier("var3"), Keyword("Take"), Keyword("While"), Identifier("var3"), LineContinuation, Keyword("Aggregate"), Identifier("var4"), Keyword("In"), Identifier("src"), LineContinuation, Keyword("Group"), Identifier("var4"), Keyword("By"), Identifier("var4"), Keyword("Into"), Identifier("var5"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Keyword("Group"), Keyword("Join"), Identifier("var6"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var6"), Keyword("Equals"), Identifier("var5"), Keyword("Into"), Identifier("var7"), Keyword("Into"), Identifier("var8"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestLinqQuery1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim src = New List(Of Boolean) Dim var3 = 1 Dim q = From var1 In src Where var1 And True _ ' Test 1 space Order By var1 Ascending Order By var1 Descending _ ' Test 2 space Select var1 Distinct _ ' Test 3 space Join var2 In src On var1 Equals var2 _ ' Test 4 space Skip var3 Skip While var3 Take var3 Take While var3 _ ' Test 1 space Aggregate var4 In src _ ' Test 1 space Group var4 By var4 Into var5 = Count() _ ' Test 1 space Group Join var6 In src On var6 Equals var5 Into var7 Into var8 = Count()" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("src"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("Dim"), Local("var3"), Operators.Equals, Number("1"), Keyword("Dim"), Local("q"), Operators.Equals, Keyword("From"), Identifier("var1"), Keyword("In"), Identifier("src"), Keyword("Where"), Identifier("var1"), Keyword("And"), Keyword("True"), LineContinuation, Comment("' Test 1 space"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Ascending"), Keyword("Order"), Keyword("By"), Identifier("var1"), Keyword("Descending"), LineContinuation, Comment("' Test 2 space"), Keyword("Select"), Identifier("var1"), Keyword("Distinct"), LineContinuation, Comment("' Test 3 space"), Keyword("Join"), Identifier("var2"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var1"), Keyword("Equals"), Identifier("var2"), LineContinuation, Comment("' Test 4 space"), Keyword("Skip"), Identifier("var3"), Keyword("Skip"), Keyword("While"), Identifier("var3"), Keyword("Take"), Identifier("var3"), Keyword("Take"), Keyword("While"), Identifier("var3"), LineContinuation, Comment("' Test 1 space"), Keyword("Aggregate"), Identifier("var4"), Keyword("In"), Identifier("src"), LineContinuation, Comment("' Test 1 space"), Keyword("Group"), Identifier("var4"), Keyword("By"), Identifier("var4"), Keyword("Into"), Identifier("var5"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen, LineContinuation, Comment("' Test 1 space"), Keyword("Group"), Keyword("Join"), Identifier("var6"), Keyword("In"), Identifier("src"), Keyword("On"), Identifier("var6"), Keyword("Equals"), Identifier("var5"), Keyword("Into"), Identifier("var7"), Keyword("Into"), Identifier("var8"), Operators.Equals, Identifier("Count"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <WorkItem(542387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542387")> <Theory, CombinatorialData> Public Async Function TestFromInQuery(testHost As TestHost) As Task Dim code = "Dim From = New List(Of Integer) Dim result = From s In From Select s" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("From"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("Dim"), Local("result"), Operators.Equals, Keyword("From"), Identifier("s"), Keyword("In"), Identifier("From"), Keyword("Select"), Identifier("s")) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword1(testHost As TestHost) As Task Dim code = "Dim Value = ""Test"" Dim Key As String = Key.Length & (Key.Length) Dim Array As String() = { Key, Key.Length } Dim o = New With {Key Key.Length, Key .Id = 1, Key Key, Key Value, Key.Empty} o = New With {Key _ Key.Length, _ Key _ .Id = 1, _ Key _ Key, _ Key _ Value, _ Key Key. _ Empty _ }" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("Value"), Operators.Equals, [String]("""Test"""), Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("String"), Operators.Equals, Identifier("Key"), Operators.Dot, Identifier("Length"), Operators.Ampersand, Punctuation.OpenParen, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Keyword("Dim"), Local("Array"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Punctuation.Comma, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseCurly, Keyword("Dim"), Local("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, Keyword("Key"), Identifier("Key"), Punctuation.Comma, Keyword("Key"), Identifier("Value"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Empty"), Punctuation.CloseCurly, Identifier("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), LineContinuation, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Identifier("Key"), Punctuation.Comma, LineContinuation, Keyword("Key"), LineContinuation, Identifier("Value"), Punctuation.Comma, LineContinuation, Keyword("Key"), Identifier("Key"), Operators.Dot, LineContinuation, Identifier("Empty"), LineContinuation, Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim Value = ""Test"" Dim Key As String = Key.Length & (Key.Length) Dim Array As String() = { Key, Key.Length } Dim o = New With {Key Key.Length, Key .Id = 1, Key Key, Key Value, Key.Empty} o = New With {Key _ ' Test Key.Length, _ ' Test Key _ ' Test .Id = 1, _ ' Test Key _ ' Test Key, _ ' Test Key _ ' Test Value, _ ' Test Key Key. _ ' Test Empty _ ' Test }" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("Value"), Operators.Equals, [String]("""Test"""), Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("String"), Operators.Equals, Identifier("Key"), Operators.Dot, Identifier("Length"), Operators.Ampersand, Punctuation.OpenParen, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseParen, Keyword("Dim"), Local("Array"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Punctuation.Comma, Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.CloseCurly, Keyword("Dim"), Local("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, Keyword("Key"), Identifier("Key"), Punctuation.Comma, Keyword("Key"), Identifier("Value"), Punctuation.Comma, Keyword("Key"), Operators.Dot, Identifier("Empty"), Punctuation.CloseCurly, Identifier("o"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Key"), Operators.Dot, Identifier("Length"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Operators.Dot, Identifier("Id"), Operators.Equals, Number("1"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Key"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), LineContinuation, Comment("' Test"), Identifier("Value"), Punctuation.Comma, LineContinuation, Comment("' Test"), Keyword("Key"), Identifier("Key"), Operators.Dot, LineContinuation, Comment("' Test"), Identifier("Empty"), LineContinuation, Comment("' Test"), Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestKeyKeyword2(testHost As TestHost) As Task Dim code = "Dim k = 10 Dim x = New With {Key If(k > 3, 2, -2).GetTypeCode} Dim y = New With {Key DirectCast(New Object(), Integer).GetTypeCode} Dim z1 = New With {Key If(True, 1,2).GetTypeCode()} Dim z2 = New With {Key CType(Nothing, Integer).GetTypeCode()} Dim Key As Integer If Key Or True Or Key = 1 Then Console.WriteLine() Dim z3() = { Key Or True, Key = 1 } Dim z4 = New List(Of Integer) From {1, 2, 3} Dim z5 As New List(Of Integer) From {1, 2, 3} Dim z6 = New List(Of Integer) With {.Capacity = 2}" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("k"), Operators.Equals, Number("10"), Keyword("Dim"), Local("x"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), ControlKeyword("If"), Punctuation.OpenParen, Identifier("k"), Operators.GreaterThan, Number("3"), Punctuation.Comma, Number("2"), Punctuation.Comma, Operators.Minus, Number("2"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.CloseCurly, Keyword("Dim"), Local("y"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Keyword("DirectCast"), Punctuation.OpenParen, Keyword("New"), Keyword("Object"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.Comma, Keyword("Integer"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.CloseCurly, Keyword("Dim"), Local("z1"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), ControlKeyword("If"), Punctuation.OpenParen, Keyword("True"), Punctuation.Comma, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Keyword("Dim"), Local("z2"), Operators.Equals, Keyword("New"), Keyword("With"), Punctuation.OpenCurly, Keyword("Key"), Keyword("CType"), Punctuation.OpenParen, Keyword("Nothing"), Punctuation.Comma, Keyword("Integer"), Punctuation.CloseParen, Operators.Dot, Identifier("GetTypeCode"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseCurly, Keyword("Dim"), Local("Key"), Keyword("As"), Keyword("Integer"), ControlKeyword("If"), Identifier("Key"), Keyword("Or"), Keyword("True"), Keyword("Or"), Identifier("Key"), Operators.Equals, Number("1"), ControlKeyword("Then"), Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("z3"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Punctuation.OpenCurly, Identifier("Key"), Keyword("Or"), Keyword("True"), Punctuation.Comma, Identifier("Key"), Operators.Equals, Number("1"), Punctuation.CloseCurly, Keyword("Dim"), Local("z4"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("From"), Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.CloseCurly, Keyword("Dim"), Local("z5"), Keyword("As"), Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("From"), Punctuation.OpenCurly, Number("1"), Punctuation.Comma, Number("2"), Punctuation.Comma, Number("3"), Punctuation.CloseCurly, Keyword("Dim"), Local("z6"), Operators.Equals, Keyword("New"), Identifier("List"), Punctuation.OpenParen, Keyword("Of"), Keyword("Integer"), Punctuation.CloseParen, Keyword("With"), Punctuation.OpenCurly, Operators.Dot, Identifier("Capacity"), Operators.Equals, Number("2"), Punctuation.CloseCurly) End Function <Theory, CombinatorialData> Public Async Function TestNamespaceDeclaration(testHost As TestHost) As Task Dim code = "Namespace N1.N2 End Namespace" Await TestAsync(code, testHost, Keyword("Namespace"), [Namespace]("N1"), Operators.Dot, [Namespace]("N2"), Keyword("End"), Keyword("Namespace")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration1(testHost As TestHost) As Task Dim code = "Class C1" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration2(testHost As TestHost) As Task Dim code = "Class C1 End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestClassDeclaration3(testHost As TestHost) As Task Dim code = "Class C1 : End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Punctuation.Colon, Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration1(testHost As TestHost) As Task Dim code = "Structure S1" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration2(testHost As TestHost) As Task Dim code = "Structure S1 : End Structure" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1"), Punctuation.Colon, Keyword("End"), Keyword("Structure")) End Function <Theory, CombinatorialData> Public Async Function TestStructDeclaration3(testHost As TestHost) As Task Dim code = "Structure S1 End Structure" Await TestAsync(code, testHost, Keyword("Structure"), Struct("S1"), Keyword("End"), Keyword("Structure")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration1(testHost As TestHost) As Task Dim code = "Interface I1" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration2(testHost As TestHost) As Task Dim code = "Interface I1 : End Interface" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1"), Punctuation.Colon, Keyword("End"), Keyword("Interface")) End Function <Theory, CombinatorialData> Public Async Function TestInterfaceDeclaration3(testHost As TestHost) As Task Dim code = "Interface I1 End Interface" Await TestAsync(code, testHost, Keyword("Interface"), [Interface]("I1"), Keyword("End"), Keyword("Interface")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration1(testHost As TestHost) As Task Dim code = "Enum E1" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration2(testHost As TestHost) As Task Dim code = "Enum E1 : End Enum" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1"), Punctuation.Colon, Keyword("End"), Keyword("Enum")) End Function <Theory, CombinatorialData> Public Async Function TestEnumDeclaration3(testHost As TestHost) As Task Dim code = "Enum E1 End Enum" Await TestAsync(code, testHost, Keyword("Enum"), [Enum]("E1"), Keyword("End"), Keyword("Enum")) End Function <Theory, CombinatorialData> Public Async Function TestDelegateSubDeclaration1(testHost As TestHost) As Task Dim code = "Public Delegate Sub Goo()" Await TestAsync(code, testHost, Keyword("Public"), Keyword("Delegate"), Keyword("Sub"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestDelegateFunctionDeclaration1(testHost As TestHost) As Task Dim code = "Public Delegate Function Goo() As Integer" Await TestAsync(code, testHost, Keyword("Public"), Keyword("Delegate"), Keyword("Function"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestTernaryConditionalExpression(testHost As TestHost) As Task Dim code = "Dim i = If(True, 1, 2)" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("i"), Operators.Equals, ControlKeyword("If"), Punctuation.OpenParen, Keyword("True"), Punctuation.Comma, Number("1"), Punctuation.Comma, Number("2"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestForStatement(testHost As TestHost) As Task Dim code = "For i = 0 To 10 Exit For" Await TestInMethodAsync(code, testHost, ControlKeyword("For"), Identifier("i"), Operators.Equals, Number("0"), ControlKeyword("To"), Number("10"), ControlKeyword("Exit"), ControlKeyword("For")) End Function <Theory, CombinatorialData> Public Async Function TestFloatLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("1.0", testHost, Number("1.0")) End Function <Theory, CombinatorialData> Public Async Function TestIntLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("1", testHost, Number("1")) End Function <Theory, CombinatorialData> Public Async Function TestDecimalLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("123D", testHost, Number("123D")) End Function <Theory, CombinatorialData> Public Async Function TestStringLiterals1(testHost As TestHost) As Task Await TestInExpressionAsync("""goo""", testHost, [String]("""goo""")) End Function <Theory, CombinatorialData> Public Async Function TestCharacterLiteral(testHost As TestHost) As Task Await TestInExpressionAsync("""f""c", testHost, [String]("""f""c")) End Function <Theory, CombinatorialData> Public Async Function TestRegression_DoUntil1(testHost As TestHost) As Task Dim code = "Do Until True" Await TestInMethodAsync(code, testHost, ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True")) End Function <Theory, CombinatorialData> Public Async Function TestComment1(testHost As TestHost) As Task Dim code = "'goo" Await TestAsync(code, testHost, Comment("'goo")) End Function <Theory, CombinatorialData> Public Async Function TestComment2(testHost As TestHost) As Task Dim code = "Class C1 'hello" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C1"), Comment("'hello")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_SingleLine(testHost As TestHost) As Task Dim code = "'''<summary>something</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Text("something"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_ExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary> ''' something ''' </summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" something"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_ExteriorTriviaInsideEndTag(testHost As TestHost) As Task Dim code = "''' <summary></ ''' summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("</"), XmlDoc.Delimiter("'''"), XmlDoc.Name(" "), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_AttributesWithExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary att1=""value1"" ''' att2=""value2""> ''' something ''' </summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Name(" "), XmlDoc.AttributeName("att1"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value1"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter("'''"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("att2"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value2"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" something"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_EmptyElementAttributesWithExteriorTrivia(testHost As TestHost) As Task Dim code = "''' <summary att1=""value1"" ''' att2=""value2"" /> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Name(" "), XmlDoc.AttributeName("att1"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value1"), XmlDoc.AttributeQuotes(""""), XmlDoc.Delimiter("'''"), XmlDoc.AttributeName(" "), XmlDoc.AttributeName("att2"), XmlDoc.Delimiter("="), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeValue("value2"), XmlDoc.AttributeQuotes(""""), XmlDoc.AttributeQuotes(" "), XmlDoc.Delimiter("/>"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_XmlCommentWithExteriorTrivia(testHost As TestHost) As Task Dim code = "'''<summary> '''<!--first '''second--> '''</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<!--"), XmlDoc.Comment("first" & vbCrLf), XmlDoc.Delimiter("'''"), XmlDoc.Comment("second"), XmlDoc.Delimiter("-->"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_CDataWithExteriorTrivia(testHost As TestHost) As Task Dim code = "'''<summary> '''<![CDATA[first '''second]]> '''</summary> Class Bar End Class" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("<![CDATA["), XmlDoc.CDataSection("first" & vbCrLf), XmlDoc.Delimiter("'''"), XmlDoc.CDataSection("second"), XmlDoc.Delimiter("]]>"), XmlDoc.Delimiter("'''"), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Class"), [Class]("Bar"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction1(testHost As TestHost) As Task Await TestAsync("''' <?", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction2(testHost As TestHost) As Task Await TestAsync("''' <??>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction3(testHost As TestHost) As Task Await TestAsync("''' <?xml", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("xml")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction4(testHost As TestHost) As Task Await TestAsync("''' <?xml version=""1.0""?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("xml"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("version=""1.0"""), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction5(testHost As TestHost) As Task Await TestAsync("''' <?goo?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDocComment_PreprocessingInstruction6(testHost As TestHost) As Task Await TestAsync("''' <?goo bar?>", testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.ProcessingInstruction("<?"), XmlDoc.ProcessingInstruction("goo"), XmlDoc.ProcessingInstruction(" "), XmlDoc.ProcessingInstruction("bar"), XmlDoc.ProcessingInstruction("?>")) End Function <Theory, CombinatorialData> Public Async Function TestIsTrue(testHost As TestHost) As Task Await TestInClassAsync(" Public Shared Operator IsTrue(c As C) As Boolean", testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("IsTrue"), Punctuation.OpenParen, Parameter("c"), Keyword("As"), Identifier("C"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean")) End Function <Theory, CombinatorialData> Public Async Function TestIsFalse(testHost As TestHost) As Task Await TestInClassAsync(" Public Shared Operator IsFalse(c As C) As Boolean", testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("IsFalse"), Punctuation.OpenParen, Parameter("c"), Keyword("As"), Identifier("C"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean")) End Function <Theory, CombinatorialData> Public Async Function TestDelegate1(testHost As TestHost) As Task Await TestAsync("Delegate Sub Goo()", testHost, Keyword("Delegate"), Keyword("Sub"), [Delegate]("Goo"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestImports1(testHost As TestHost) As Task Dim code = "Imports Goo Imports Bar" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("Goo"), Keyword("Imports"), Identifier("Bar")) End Function ''' <summary> ''' Clear Syntax Error ''' </summary> <Theory, CombinatorialData> Public Async Function TestImports2(testHost As TestHost) As Task Dim code = "Imports Imports Bar" Await TestAsync(code, testHost, Keyword("Imports"), Keyword("Imports"), Identifier("Bar")) End Function <Theory, CombinatorialData> Public Async Function TestImports3(testHost As TestHost) As Task Dim code = "Imports Goo=Baz Imports Bar=Quux" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("Goo"), Operators.Equals, Identifier("Baz"), Keyword("Imports"), Identifier("Bar"), Operators.Equals, Identifier("Quux")) End Function <Theory, CombinatorialData> Public Async Function TestImports4(testHost As TestHost) As Task Dim code = "Imports System.Text" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("System"), Operators.Dot, Identifier("Text")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function '''<summary> ''' Broken XmlElement should classify ''' </summary> <Theory, CombinatorialData> Public Async Function TestXmlElement3(testHost As TestHost) As Task Await TestInExpressionAsync("<goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function '''<summary> ''' Broken end only element should still classify ''' </summary> <Theory, CombinatorialData> Public Async Function TestXmlElement4(testHost As TestHost) As Task Await TestInExpressionAsync("</goo>", testHost, VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar></goo.bar>", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("goo.bar"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement6(testHost As TestHost) As Task Await TestInExpressionAsync("<goo:bar>hello</goo:bar>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter(">"), VBXmlText("hello"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlName(":"), VBXmlName("bar"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElement7(testHost As TestHost) As Task Await TestInExpressionAsync("<goo.bar />", testHost, VBXmlDelimiter("<"), VBXmlName("goo.bar"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded1(testHost As TestHost) As Task Await TestInExpressionAsync("<goo><%= bar %></goo>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("</"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded3(testHost As TestHost) As Task Await TestInExpressionAsync("<<%= bar %>/>", testHost, VBXmlDelimiter("<"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded4(testHost As TestHost) As Task Await TestInExpressionAsync("<goo <%= bar %>=""42""/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("42"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlEmbedded5(testHost As TestHost) As Task Await TestInExpressionAsync("<goo a1=<%= bar %>/>", testHost, VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlAttributeName("a1"), VBXmlDelimiter("="), VBXmlEmbeddedExpression("<%="), Identifier("bar"), VBXmlEmbeddedExpression("%>"), VBXmlDelimiter("/>")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment1(testHost As TestHost) As Task Await TestInExpressionAsync("<!---->", testHost, VBXmlDelimiter("<!--"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment2(testHost As TestHost) As Task Await TestInExpressionAsync("<!--goo-->", testHost, VBXmlDelimiter("<!--"), VBXmlComment("goo"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlComment3(testHost As TestHost) As Task Await TestInExpressionAsync("<a><!--goo--></a>", testHost, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment("goo"), VBXmlDelimiter("-->"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlPreprocessingInstruction2(testHost As TestHost) As Task Await TestInExpressionAsync("<a><?pi value=2?></a>", testHost, VBXmlDelimiter("<"), VBXmlName("a"), VBXmlDelimiter(">"), VBXmlDelimiter("<?"), VBXmlName("pi"), VBXmlProcessingInstruction("value=2"), VBXmlDelimiter("?>"), VBXmlDelimiter("</"), VBXmlName("a"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDescendantsMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x...<goo>", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("."), VBXmlDelimiter("."), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlElementMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x.<goo>", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("<"), VBXmlName("goo"), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeMemberAccess1(testHost As TestHost) As Task Await TestInExpressionAsync("x.@goo", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("goo")) End Function <Theory, CombinatorialData> Public Async Function TestXmlAttributeMemberAccess2(testHost As TestHost) As Task Await TestInExpressionAsync("x.@goo:bar", testHost, Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("goo"), VBXmlAttributeName(":"), VBXmlAttributeName("bar")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorReference(testHost As TestHost) As Task Await TestInNamespaceAsync("#R ""Ref""", testHost, PPKeyword("#"), PPKeyword("R"), [String]("""Ref""")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorConst1(testHost As TestHost) As Task Await TestInNamespaceAsync("#Const Goo = 1", testHost, PPKeyword("#"), PPKeyword("Const"), Identifier("Goo"), Operators.Equals, Number("1")) End Function Public Async Function TestPreprocessorConst2(testHost As TestHost) As Task Await TestInNamespaceAsync("#Const DebugCode = True", testHost, PPKeyword("#"), PPKeyword("Const"), Identifier("DebugCode"), Operators.Equals, Keyword("True")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorIfThen1(testHost As TestHost) As Task Await TestInNamespaceAsync("#If Goo Then", testHost, PPKeyword("#"), PPKeyword("If"), Identifier("Goo"), PPKeyword("Then")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorElseIf1(testHost As TestHost) As Task Await TestInNamespaceAsync("#ElseIf Goo Then", testHost, PPKeyword("#"), PPKeyword("ElseIf"), Identifier("Goo"), PPKeyword("Then")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorElse1(testHost As TestHost) As Task Await TestInNamespaceAsync("#Else", testHost, PPKeyword("#"), PPKeyword("Else")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorEndIf1(testHost As TestHost) As Task Await TestInNamespaceAsync("#End If", testHost, PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalSource1(testHost As TestHost) As Task Await TestInNamespaceAsync("#ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30)", testHost, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum1(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ""{12345678-1234-1234-1234-123456789abc}"", _ ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"")" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ' Test ""{12345678-1234-1234-1234-123456789abc}"", _ ' Test ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"")" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, Comment("' Test"), [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, Comment("' Test"), [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum2(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ""{12345678-1234-1234-1234-123456789abc}"", _ ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"") Module Test Sub Main() #ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30) Console.WriteLine(""In test.aspx"") #End ExternalSource End Sub End Module" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen, Keyword("Module"), [Module]("Test"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, [String]("""In test.aspx"""), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestPreprocessorExternalChecksum2CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "#ExternalChecksum(""c:\wwwroot\inetpub\test.aspx"", _ ' Test 1 ""{12345678-1234-1234-1234-123456789abc}"", _ ' Test 2 ""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"") Module Test Sub Main() #ExternalSource(""c:\wwwroot\inetpub\test.aspx"", 30) Console.WriteLine(""In test.aspx"") #End ExternalSource End Sub End Module" Await TestInNamespaceAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalChecksum"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, LineContinuation, Comment("' Test 1"), [String]("""{12345678-1234-1234-1234-123456789abc}"""), Punctuation.Comma, LineContinuation, Comment("' Test 2"), [String]("""1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484"""), Punctuation.CloseParen, Keyword("Module"), [Module]("Test"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""c:\wwwroot\inetpub\test.aspx"""), Punctuation.Comma, Number("30"), Punctuation.CloseParen, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, [String]("""In test.aspx"""), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_1(testHost As TestHost) As Task Dim code = "Class PreprocessorNoContext Dim Region Dim ExternalSource End Class #Region ""Test"" #End Region #Region ""Test"" ' comment #End Region ' comment #Region ""Test"" REM comment #End Region REM comment # _ Region ""Test"" # _ End Region # _ Region _ ""Test"" # _ End _ Region" Await TestAsync(code, testHost, Keyword("Class"), [Class]("PreprocessorNoContext"), Keyword("Dim"), Field("Region"), Keyword("Dim"), Field("ExternalSource"), Keyword("End"), Keyword("Class"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' comment"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("REM comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("REM comment"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), LineContinuation, [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_1CommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Class PreprocessorNoContext Dim Region Dim ExternalSource End Class #Region ""Test"" #End Region #Region ""Test"" ' comment #End Region ' comment #Region ""Test"" REM comment #End Region REM comment # _ ' Test 1 Region ""Test"" # _ ' Test 2 End Region # _ ' Test 3 Region _ ' Test 4 ""Test"" # _ ' Test 5 End _ ' Test 6 Region" Await TestAsync(code, testHost, Keyword("Class"), [Class]("PreprocessorNoContext"), Keyword("Dim"), Field("Region"), Keyword("Dim"), Field("ExternalSource"), Keyword("End"), Keyword("Class"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' comment"), PPKeyword("#"), PPKeyword("Region"), [String]("""Test"""), Comment("REM comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("REM comment"), PPKeyword("#"), LineContinuation, Comment("' Test 1"), PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, Comment("' Test 2"), PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, Comment("' Test 3"), PPKeyword("Region"), LineContinuation, Comment("' Test 4"), [String]("""Test"""), PPKeyword("#"), LineContinuation, Comment("' Test 5"), PPKeyword("End"), LineContinuation, Comment("' Test 6"), PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2641_2(testHost As TestHost) As Task Dim code = "#ExternalSource(""Test.vb"", 123) #End ExternalSource #ExternalSource(""Test.vb"", 123) ' comment #End ExternalSource REM comment # _ ExternalSource _ ( _ ""Test.vb"" _ , _ 123) # _ End _ ExternalSource" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""Test.vb"""), Punctuation.Comma, Number("123"), Punctuation.CloseParen, PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), PPKeyword("#"), PPKeyword("ExternalSource"), Punctuation.OpenParen, [String]("""Test.vb"""), Punctuation.Comma, Number("123"), Punctuation.CloseParen, Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("ExternalSource"), Comment("REM comment"), PPKeyword("#"), LineContinuation, PPKeyword("ExternalSource"), LineContinuation, Punctuation.OpenParen, LineContinuation, [String]("""Test.vb"""), LineContinuation, Punctuation.Comma, LineContinuation, Number("123"), Punctuation.CloseParen, PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("ExternalSource")) End Function <Theory, CombinatorialData> Public Async Function TestBug2640(testHost As TestHost) As Task Dim code = "# _ Region ""Test"" # _ End Region # _ Region _ ""Test"" # _ End _ Region" Await TestAsync(code, testHost, PPKeyword("#"), LineContinuation, PPKeyword("Region"), [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), PPKeyword("Region"), PPKeyword("#"), LineContinuation, PPKeyword("Region"), LineContinuation, [String]("""Test"""), PPKeyword("#"), LineContinuation, PPKeyword("End"), LineContinuation, PPKeyword("Region")) End Function <Theory, CombinatorialData> Public Async Function TestBug2638(testHost As TestHost) As Task Dim code = "Module M Sub Main() Dim dt = #1/1/2000# End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("M"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("dt"), Operators.Equals, Number("#1/1/2000#"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug2562(testHost As TestHost) As Task Dim code = "Module Program Sub Main(args As String()) #region ""Goo"" #End region REM dfkjslfkdsjf End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Punctuation.OpenParen, Parameter("args"), Keyword("As"), Keyword("String"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseParen, PPKeyword("#"), PPKeyword("region"), [String]("""Goo"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("region"), Comment("REM dfkjslfkdsjf"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug3004(testHost As TestHost) As Task Dim code = "''' <summary> ''' &#65; ''' </summary> Module M End Module" Await TestAsync(code, testHost, XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("<"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.EntityReference("&#65;"), XmlDoc.Delimiter("'''"), XmlDoc.Text(" "), XmlDoc.Delimiter("</"), XmlDoc.Name("summary"), XmlDoc.Delimiter(">"), Keyword("Module"), [Module]("M"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBug3006(testHost As TestHost) As Task Dim code = "#If True Then ' comment #End If" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("If"), Keyword("True"), PPKeyword("Then"), Comment("' comment"), PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestBug3008(testHost As TestHost) As Task Dim code = "#If #12/2/2010# = #12/2/2010# Then #End If" Await TestAsync(code, testHost, PPKeyword("#"), PPKeyword("If"), Number("#12/2/2010#"), Operators.Equals, Number("#12/2/2010#"), PPKeyword("Then"), PPKeyword("#"), PPKeyword("End"), PPKeyword("If")) End Function <Theory, CombinatorialData> Public Async Function TestBug927678(testHost As TestHost) As Task Dim code = "'This is not usually a " & vbCrLf & "'collapsible comment block" & vbCrLf & "x = 2" Await TestInMethodAsync(code, testHost, Comment("'This is not usually a "), Comment("'collapsible comment block"), Identifier("x"), Operators.Equals, Number("2")) End Function <Theory, CombinatorialData> Public Async Function TestAttribute(testHost As TestHost) As Task Dim code = "<Assembly: Goo()>" Await TestAsync(code, testHost, Punctuation.OpenAngle, Keyword("Assembly"), Punctuation.Colon, Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Punctuation.CloseAngle) End Function <Theory, CombinatorialData> Public Async Function TestAngleBracketsOnGenericConstraints_Bug932262(testHost As TestHost) As Task Dim code = "Class C(Of T As A(Of T)) End Class" Await TestAsync(code, testHost, Keyword("Class"), [Class]("C"), Punctuation.OpenParen, Keyword("Of"), TypeParameter("T"), Keyword("As"), Identifier("A"), Punctuation.OpenParen, Keyword("Of"), Identifier("T"), Punctuation.CloseParen, Punctuation.CloseParen, Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestIntegerAsContextualKeyword(testHost As TestHost) As Task Dim code = "Sub CallMeInteger(ByVal [Integer] As Integer) CallMeInteger(Integer:=1) CallMeInteger(Integer _ := _ 1) End Sub Dim [Class] As Integer" Await TestInClassAsync(code, testHost, Keyword("Sub"), Method("CallMeInteger"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("[Integer]"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), LineContinuation, Operators.ColonEquals, LineContinuation, Number("1"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("Dim"), Field("[Class]"), Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestIntegerAsContextualKeywordCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Sub CallMeInteger(ByVal [Integer] As Integer) CallMeInteger(Integer:=1) CallMeInteger(Integer _ ' Test 1 := _ ' Test 2 1) End Sub Dim [Class] As Integer" Await TestInClassAsync(code, testHost, Keyword("Sub"), Method("CallMeInteger"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("[Integer]"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeInteger"), Punctuation.OpenParen, Identifier("Integer"), LineContinuation, Comment("' Test 1"), Operators.ColonEquals, LineContinuation, Comment("' Test 2"), Number("1"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("Dim"), Field("[Class]"), Keyword("As"), Keyword("Integer")) End Function <Theory, CombinatorialData> Public Async Function TestIndexStrings(testHost As TestHost) As Task Dim code = "Default ReadOnly Property IndexMe(ByVal arg As String) As Integer Get With Me Dim t = !String t = ! _ String t = .Class t = . _ Class End With End Get End Property" Await TestAsync(code, testHost, Keyword("Default"), Keyword("ReadOnly"), Keyword("Property"), [Property]("IndexMe"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("arg"), Keyword("As"), Keyword("String"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), Keyword("Get"), Keyword("With"), Keyword("Me"), Keyword("Dim"), Local("t"), Operators.Equals, Operators.Exclamation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Exclamation, LineContinuation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Dot, Identifier("Class"), Identifier("t"), Operators.Equals, Operators.Dot, LineContinuation, Identifier("Class"), Keyword("End"), Keyword("With"), Keyword("End"), Keyword("Get"), Keyword("End"), Keyword("Property")) End Function <Theory, CombinatorialData> Public Async Function TestIndexStringsCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Default ReadOnly Property IndexMe(ByVal arg As String) As Integer Get With Me Dim t = !String t = ! _ ' Test 1 String t = .Class t = . _ ' Test 2 Class End With End Get End Property" Await TestAsync(code, testHost, Keyword("Default"), Keyword("ReadOnly"), Keyword("Property"), [Property]("IndexMe"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("arg"), Keyword("As"), Keyword("String"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), Keyword("Get"), Keyword("With"), Keyword("Me"), Keyword("Dim"), Local("t"), Operators.Equals, Operators.Exclamation, Identifier("String"), Identifier("t"), Operators.Equals, Operators.Exclamation, LineContinuation, Comment("' Test 1"), Identifier("String"), Identifier("t"), Operators.Equals, Operators.Dot, Identifier("Class"), Identifier("t"), Operators.Equals, Operators.Dot, LineContinuation, Comment("' Test 2"), Identifier("Class"), Keyword("End"), Keyword("With"), Keyword("End"), Keyword("Get"), Keyword("End"), Keyword("Property")) End Function <Theory, CombinatorialData> Public Async Function TestMyIsIdentifierOnSyntaxLevel(testHost As TestHost) As Task Dim code = "Dim My Dim var = My.Application.GetEnvironmentVariable(""test"") Sub CallMeMy(ByVal My As Integer) CallMeMy(My:=1) CallMeMy(My _ := _ 1) My.ToString() With Me .My = 1 . _ My _ = 1 !My = Nothing ! _ My _ = Nothing End With Me.My.ToString() Me. _ My.ToString() Me.My = 1 Me. _ My = 1 End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("My"), Keyword("Dim"), Field("var"), Operators.Equals, Identifier("My"), Operators.Dot, Identifier("Application"), Operators.Dot, Identifier("GetEnvironmentVariable"), Punctuation.OpenParen, [String]("""test"""), Punctuation.CloseParen, Keyword("Sub"), Method("CallMeMy"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("My"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), LineContinuation, Operators.ColonEquals, LineContinuation, Number("1"), Punctuation.CloseParen, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Operators.Dot, LineContinuation, Identifier("My"), LineContinuation, Operators.Equals, Number("1"), Operators.Exclamation, Identifier("My"), Operators.Equals, Keyword("Nothing"), Operators.Exclamation, LineContinuation, Identifier("My"), LineContinuation, Operators.Equals, Keyword("Nothing"), Keyword("End"), Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, LineContinuation, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Keyword("Me"), Operators.Dot, LineContinuation, Identifier("My"), Operators.Equals, Number("1"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestMyIsIdentifierOnSyntaxLevelCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = "Dim My Dim var = My.Application.GetEnvironmentVariable(""test"") Sub CallMeMy(ByVal My As Integer) CallMeMy(My:=1) CallMeMy(My _ ' Test 1 := _ ' Test 2 1) My.ToString() With Me .My = 1 . _ ' Test 3 My _ ' Test 4 = 1 !My = Nothing ! _ ' Test 5 My _ ' Test 6 = Nothing End With Me.My.ToString() Me. _ ' Test 7 My.ToString() Me.My = 1 Me. _ ' Test 8 My = 1 End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("My"), Keyword("Dim"), Field("var"), Operators.Equals, Identifier("My"), Operators.Dot, Identifier("Application"), Operators.Dot, Identifier("GetEnvironmentVariable"), Punctuation.OpenParen, [String]("""test"""), Punctuation.CloseParen, Keyword("Sub"), Method("CallMeMy"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("My"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), Operators.ColonEquals, Number("1"), Punctuation.CloseParen, Identifier("CallMeMy"), Punctuation.OpenParen, Identifier("My"), LineContinuation, Comment("' Test 1"), Operators.ColonEquals, LineContinuation, Comment("' Test 2"), Number("1"), Punctuation.CloseParen, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Operators.Dot, LineContinuation, Comment("' Test 3"), Identifier("My"), LineContinuation, Comment("' Test 4"), Operators.Equals, Number("1"), Operators.Exclamation, Identifier("My"), Operators.Equals, Keyword("Nothing"), Operators.Exclamation, LineContinuation, Comment("' Test 5"), Identifier("My"), LineContinuation, Comment("' Test 6"), Operators.Equals, Keyword("Nothing"), Keyword("End"), Keyword("With"), Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, LineContinuation, Comment("' Test 7"), Identifier("My"), Operators.Dot, Identifier("ToString"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Me"), Operators.Dot, Identifier("My"), Operators.Equals, Number("1"), Keyword("Me"), Operators.Dot, LineContinuation, Comment("' Test 8"), Identifier("My"), Operators.Equals, Number("1"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestIsTrueIsFalse(testHost As TestHost) As Task Dim code = "Class IsTrueIsFalseTests Dim IsTrue Dim IsFalse Shared Operator IsTrue(ByVal x As IsTrueIsFalseTests) As Boolean End Operator Shared Operator IsFalse(ByVal x As IsTrueIsFalseTests) As Boolean End Operator End Class" Await TestInClassAsync(code, testHost, Keyword("Class"), [Class]("IsTrueIsFalseTests"), Keyword("Dim"), Field("IsTrue"), Keyword("Dim"), Field("IsFalse"), Keyword("Shared"), Keyword("Operator"), Keyword("IsTrue"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("x"), Keyword("As"), Identifier("IsTrueIsFalseTests"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean"), Keyword("End"), Keyword("Operator"), Keyword("Shared"), Keyword("Operator"), Keyword("IsFalse"), Punctuation.OpenParen, Keyword("ByVal"), Parameter("x"), Keyword("As"), Identifier("IsTrueIsFalseTests"), Punctuation.CloseParen, Keyword("As"), Keyword("Boolean"), Keyword("End"), Keyword("Operator"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestDeclareAnsiAutoUnicode(testHost As TestHost) As Task Dim code = " Dim Ansi Dim Unicode Dim Auto Declare Ansi Sub AnsiTest Lib ""Test.dll"" () Declare Auto Sub AutoTest Lib ""Test.dll"" () Declare Unicode Sub UnicodeTest Lib ""Test.dll"" () Declare _ Ansi Sub AnsiTest2 Lib ""Test.dll"" () Declare _ Auto Sub AutoTest2 Lib ""Test.dll"" () Declare _ Unicode Sub UnicodeTest2 Lib ""Test.dll"" ()" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Ansi"), Keyword("Dim"), Field("Unicode"), Keyword("Dim"), Field("Auto"), Keyword("Declare"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Auto"), Keyword("Sub"), Method("AutoTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestDeclareAnsiAutoUnicodeCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Ansi Dim Unicode Dim Auto Declare Ansi Sub AnsiTest Lib ""Test.dll"" () Declare Auto Sub AutoTest Lib ""Test.dll"" () Declare Unicode Sub UnicodeTest Lib ""Test.dll"" () Declare _ ' Test 1 Ansi Sub AnsiTest2 Lib ""Test.dll"" () Declare _ ' Test 2 Auto Sub AutoTest2 Lib ""Test.dll"" () Declare _ ' Test 3 Unicode Sub UnicodeTest2 Lib ""Test.dll"" ()" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Ansi"), Keyword("Dim"), Field("Unicode"), Keyword("Dim"), Field("Auto"), Keyword("Declare"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 1"), Keyword("Ansi"), Keyword("Sub"), Method("AnsiTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 2"), Keyword("Auto"), Keyword("Sub"), Method("AutoTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Declare"), LineContinuation, Comment("' Test 3"), Keyword("Unicode"), Keyword("Sub"), Method("UnicodeTest2"), Keyword("Lib"), [String]("""Test.dll"""), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestUntil(testHost As TestHost) As Task Dim code = " Dim Until Sub TestSub() Do Loop Until True Do Loop _ Until True Do Until True Loop Do _ Until True Loop End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Until"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, ControlKeyword("Do"), ControlKeyword("Loop"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Loop"), LineContinuation, ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), ControlKeyword("Do"), LineContinuation, ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestUntilCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Until Sub TestSub() Do Loop Until True Do Loop _ ' Test 1 Until True Do Until True Loop Do _ ' Test 2 Until True Loop End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Until"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, ControlKeyword("Do"), ControlKeyword("Loop"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Loop"), LineContinuation, Comment("' Test 1"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Do"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), ControlKeyword("Do"), LineContinuation, Comment("' Test 2"), ControlKeyword("Until"), Keyword("True"), ControlKeyword("Loop"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestPreserve(testHost As TestHost) As Task Dim code = " Dim Preserve Sub TestSub() Dim arr As Integer() = Nothing ReDim Preserve arr(0) ReDim _ Preserve arr(0) End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Preserve"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("arr"), Keyword("As"), Keyword("Integer"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Keyword("Nothing"), Keyword("ReDim"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("ReDim"), LineContinuation, Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestPreserveCommentsAfterLineContinuation(testHost As TestHost) As Task Dim code = " Dim Preserve Sub TestSub() Dim arr As Integer() = Nothing ReDim Preserve arr(0) ReDim _ ' Test Preserve arr(0) End Sub" Await TestInClassAsync(code, testHost, Keyword("Dim"), Field("Preserve"), Keyword("Sub"), Method("TestSub"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("arr"), Keyword("As"), Keyword("Integer"), Punctuation.OpenParen, Punctuation.CloseParen, Operators.Equals, Keyword("Nothing"), Keyword("ReDim"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("ReDim"), LineContinuation, Comment("' Test"), Keyword("Preserve"), Identifier("arr"), Punctuation.OpenParen, Number("0"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestSkippedTextAsTokens(testHost As TestHost) As Task Dim code = "Module Program Sub Test(ByVal readOnly As Boolean) End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Test"), Punctuation.OpenParen, Keyword("ByVal"), Keyword("readOnly"), Parameter("As"), Keyword("Boolean"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(538647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538647")> Public Async Function TestRegression4315_VariableNamesClassifiedAsType(testHost As TestHost) As Task Dim code = "Module M Sub S() Dim goo End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("M"), Keyword("Sub"), Method("S"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("goo"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(539203, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539203")> Public Async Function TestColonTrivia(testHost As TestHost) As Task Await TestInMethodAsync(" : Console.WriteLine()", testHost, Punctuation.Colon, Identifier("Console"), Operators.Dot, Identifier("WriteLine"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> <WorkItem(539642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539642")> Public Async Function TestFromInCollectionInitializer1(testHost As TestHost) As Task Await TestInMethodAsync("Dim y = New Goo() From", testHost, Keyword("Dim"), Local("y"), Operators.Equals, Keyword("New"), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("From")) End Function <Theory, CombinatorialData> <WorkItem(539642, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539642")> Public Async Function TestFromInCollectionInitializer2(testHost As TestHost) As Task Await TestInMethodAsync("Dim y As New Goo() From", testHost, Keyword("Dim"), Local("y"), Keyword("As"), Keyword("New"), Identifier("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("From")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport1(testHost As TestHost) As Task Await TestAsync("Imports <x", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlName("x")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport2(testHost As TestHost) As Task Await TestAsync("Imports <xml", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlName("xml")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport3(testHost As TestHost) As Task Await TestAsync("Imports <xmlns", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport4(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport5(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport6(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("=")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestPartiallyTypedXmlNamespaceImport7(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=""http://goo""", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("http://goo"), VBXmlAttributeQuotes("""")) End Function <Theory, CombinatorialData> <WorkItem(539779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539779")> Public Async Function TestFullyTypedXmlNamespaceImport(testHost As TestHost) As Task Await TestAsync("Imports <xmlns:ns=""http://goo"">", testHost, Keyword("Imports"), VBXmlDelimiter("<"), VBXmlAttributeName("xmlns"), VBXmlAttributeName(":"), VBXmlAttributeName("ns"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("http://goo"), VBXmlAttributeQuotes(""""), VBXmlDelimiter(">")) End Function <Theory, CombinatorialData> Public Async Function TestGetXmlNamespaceExpression(testHost As TestHost) As Task Await TestInExpressionAsync("GetXmlNamespace(Name)", testHost, Keyword("GetXmlNamespace"), Punctuation.OpenParen, VBXmlName("Name"), Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestGetXmlNamespaceExpressionWithNoName(testHost As TestHost) As Task Await TestInExpressionAsync("GetXmlNamespace()", testHost, Keyword("GetXmlNamespace"), Punctuation.OpenParen, Punctuation.CloseParen) End Function <Theory, CombinatorialData> Public Async Function TestClassifyXmlDocumentFollowingMisc(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml ?><x></x><!--h-->", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlDelimiter("?>"), VBXmlDelimiter("<"), VBXmlName("x"), VBXmlDelimiter(">"), VBXmlDelimiter("</"), VBXmlName("x"), VBXmlDelimiter(">"), VBXmlDelimiter("<!--"), VBXmlComment("h"), VBXmlDelimiter("-->")) End Function <Theory, CombinatorialData> Public Async Function TestXmlDeclaration(testHost As TestHost) As Task Await TestInExpressionAsync("<?xml version=""1.0""?>", testHost, VBXmlDelimiter("<?"), VBXmlName("xml"), VBXmlAttributeName("version"), VBXmlDelimiter("="), VBXmlAttributeQuotes(""""), VBXmlAttributeValue("1.0"), VBXmlAttributeQuotes(""""), VBXmlDelimiter("?>")) End Function <Theory, CombinatorialData> Public Async Function TestEnableWarningDirective(testHost As TestHost) As Task Dim code = "Module Program Sub Main #Enable Warning BC123, [bc456], SomeId End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), PPKeyword("Enable"), PPKeyword("Warning"), Identifier("BC123"), Punctuation.Comma, Identifier("[bc456]"), Punctuation.Comma, Identifier("SomeId"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestDisableWarningDirective(testHost As TestHost) As Task Dim code = "Module Program Sub Main #Disable Warning End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), PPKeyword("Disable"), PPKeyword("Warning"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestBadWarningDirectives(testHost As TestHost) As Task Dim code = "Module Program Sub Main #warning End Sub #Enable blah Warning End Module #Disable bc123 Warning #Enable #Disable Warning blah" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), PPKeyword("#"), Identifier("warning"), Keyword("End"), Keyword("Sub"), PPKeyword("#"), PPKeyword("Enable"), Identifier("blah"), Identifier("Warning"), Keyword("End"), Keyword("Module"), PPKeyword("#"), PPKeyword("Disable"), Identifier("bc123"), Identifier("Warning"), PPKeyword("#"), PPKeyword("Enable"), PPKeyword("#"), PPKeyword("Disable"), PPKeyword("Warning"), Identifier("blah")) End Function <Theory, CombinatorialData> Public Async Function TestInterpolatedString1(testHost As TestHost) As Task Dim code = "Module Program Sub Main Dim s = $""Hello, {name,10:F}."" End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Keyword("Dim"), Local("s"), Operators.Equals, [String]("$"""), [String]("Hello, "), Punctuation.OpenCurly, Identifier("name"), Punctuation.Comma, Number("10"), Punctuation.Colon, [String]("F"), Punctuation.CloseCurly, [String]("."), [String](""""), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> Public Async Function TestInterpolatedString2(testHost As TestHost) As Task Dim code = "Module Program Sub Main Dim s = $""{x}, {y}"" End Sub End Module" Await TestAsync(code, testHost, Keyword("Module"), [Module]("Program"), Keyword("Sub"), Method("Main"), Keyword("Dim"), Local("s"), Operators.Equals, [String]("$"""), Punctuation.OpenCurly, Identifier("x"), Punctuation.CloseCurly, [String](", "), Punctuation.OpenCurly, Identifier("y"), Punctuation.CloseCurly, [String](""""), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module")) End Function <Theory, CombinatorialData> <WorkItem(2126, "https://github.com/dotnet/roslyn/issues/2126")> Public Async Function CommentBeforeXmlAccessExpression(testHost As TestHost) As Task Dim code = " ' Comment x.@Name = ""Text"" ' Comment" Await TestInMethodAsync( className:="C", methodName:="M", code, testHost, Comment("' Comment"), Identifier("x"), VBXmlDelimiter("."), VBXmlDelimiter("@"), VBXmlAttributeName("Name"), Operators.Equals, [String]("""Text"""), Comment("' Comment")) End Function <Theory, CombinatorialData> <WorkItem(3291, "https://github.com/dotnet/roslyn/issues/3291")> Public Async Function TestCommentOnCollapsedEndRegion(testHost As TestHost) As Task Dim code = "#Region ""Stuff"" #End Region ' Stuff" Await TestAsync( code, testHost, PPKeyword("#"), PPKeyword("Region"), [String]("""Stuff"""), PPKeyword("#"), PPKeyword("End"), PPKeyword("Region"), Comment("' Stuff")) End Function <Theory, CombinatorialData> Public Async Function TestConflictMarkers1(testHost As TestHost) As Task Dim code = "interface I <<<<<<< Start sub Goo() ======= sub Bar() >>>>>>> End end interface" Await TestAsync( code, testHost, Keyword("interface"), [Interface]("I"), Comment("<<<<<<< Start"), Keyword("sub"), Method("Goo"), Punctuation.OpenParen, Punctuation.CloseParen, Comment("======="), Keyword("sub"), Identifier("Bar"), Punctuation.OpenParen, Punctuation.CloseParen, Comment(">>>>>>> End"), Keyword("end"), Keyword("interface")) End Function <Theory, CombinatorialData> Public Async Function TestConstField(testHost As TestHost) As Task Dim code = "Const Number = 42" Await TestInClassAsync(code, testHost, Keyword("Const"), Constant("Number"), [Static]("Number"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestLocalConst(testHost As TestHost) As Task Dim code = "Const Number = 42" Await TestInMethodAsync(code, testHost, Keyword("Const"), Constant("Number"), Operators.Equals, Number("42")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInLocals(testHost As TestHost) As Task Dim code = "Dim x$ = ""23"" x$ = ""19""" Await TestInMethodAsync(code, testHost, Keyword("Dim"), Local("x$"), Operators.Equals, [String]("""23"""), Identifier("x$"), Operators.Equals, [String]("""19""")) End Function <Theory, CombinatorialData> Public Async Function TestModifiedIdentifiersInFields(testHost As TestHost) As Task Dim code = "Const x$ = ""23"" Dim y$ = x$" Await TestInClassAsync(code, testHost, Keyword("Const"), Constant("x$"), [Static]("x$"), Operators.Equals, [String]("""23"""), Keyword("Dim"), Field("y$"), Operators.Equals, Identifier("x$")) End Function <Theory, CombinatorialData> Public Async Function TestFunctionNamesWithTypeCharacters(testHost As TestHost) As Task Dim code = "Function x%() x% = 42 End Function" Await TestInClassAsync(code, testHost, Keyword("Function"), Method("x%"), Punctuation.OpenParen, Punctuation.CloseParen, Identifier("x%"), Operators.Equals, Number("42"), Keyword("End"), Keyword("Function")) End Function <Theory, CombinatorialData> Public Async Function TestExtensionMethod(testHost As TestHost) As Task Dim code = " Imports System.Runtime.CompilerServices Module M <Extension> Sub Square(ByRef x As Integer) x = x * x End Sub End Module Class C Sub Test() Dim x = 42 x.Square() M.Square(x) End Sub End Class" Await TestAsync(code, testHost, Keyword("Imports"), Identifier("System"), Operators.Dot, Identifier("Runtime"), Operators.Dot, Identifier("CompilerServices"), Keyword("Module"), [Module]("M"), Punctuation.OpenAngle, Identifier("Extension"), Punctuation.CloseAngle, Keyword("Sub"), Method("Square"), Punctuation.OpenParen, Keyword("ByRef"), Parameter("x"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Identifier("x"), Operators.Equals, Identifier("x"), Operators.Asterisk, Identifier("x"), Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Module"), Keyword("Class"), [Class]("C"), Keyword("Sub"), Method("Test"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("Dim"), Local("x"), Operators.Equals, Number("42"), Identifier("x"), Operators.Dot, Identifier("Square"), Punctuation.OpenParen, Punctuation.CloseParen, Identifier("M"), Operators.Dot, Identifier("Square"), Punctuation.OpenParen, Identifier("x"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub"), Keyword("End"), Keyword("Class")) End Function <Theory, CombinatorialData> Public Async Function TestSimpleEvent(testHost As TestHost) As Task Dim code = " Event E(x As Integer) Sub M() RaiseEvent E(42) End Sub" Await TestInClassAsync(code, testHost, Keyword("Event"), [Event]("E"), Punctuation.OpenParen, Parameter("x"), Keyword("As"), Keyword("Integer"), Punctuation.CloseParen, Keyword("Sub"), Method("M"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("RaiseEvent"), Identifier("E"), Punctuation.OpenParen, Number("42"), Punctuation.CloseParen, Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestOperators(testHost As TestHost) As Task Dim code = " Public Shared Operator Not(t As Test) As Test Return New Test() End Operator Public Shared Operator +(t1 As Test, t2 As Test) As Integer Return 1 End Operator" Await TestInClassAsync(code, testHost, Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Keyword("Not"), Punctuation.OpenParen, Parameter("t"), Keyword("As"), Identifier("Test"), Punctuation.CloseParen, Keyword("As"), Identifier("Test"), ControlKeyword("Return"), Keyword("New"), Identifier("Test"), Punctuation.OpenParen, Punctuation.CloseParen, Keyword("End"), Keyword("Operator"), Keyword("Public"), Keyword("Shared"), Keyword("Operator"), Operators.Plus, Punctuation.OpenParen, Parameter("t1"), Keyword("As"), Identifier("Test"), Punctuation.Comma, Parameter("t2"), Keyword("As"), Identifier("Test"), Punctuation.CloseParen, Keyword("As"), Keyword("Integer"), ControlKeyword("Return"), Number("1"), Keyword("End"), Keyword("Operator")) End Function <Theory, CombinatorialData> Public Async Function TestLabelName(testHost As TestHost) As Task Dim code = "Sub Main E: GoTo E End Sub" Await TestAsync(code, testHost, Keyword("Sub"), Method("Main"), Label("E"), Punctuation.Colon, ControlKeyword("GoTo"), Identifier("E"), Keyword("End"), Keyword("Sub")) End Function <Theory, CombinatorialData> Public Async Function TestCatchStatement(testHost As TestHost) As Task Dim code = "Try Catch ex As Exception End Try" Await TestInMethodAsync(code, testHost, ControlKeyword("Try"), ControlKeyword("Catch"), Local("ex"), Keyword("As"), Identifier("Exception"), ControlKeyword("End"), ControlKeyword("Try")) End Function End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/ObjectPools/PooledDisposer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PooledObjects { [NonCopyable] internal readonly struct PooledDisposer<TPoolable> : IDisposable where TPoolable : class, IPooled { private readonly TPoolable _pooledObject; public PooledDisposer(TPoolable instance) => _pooledObject = instance; void IDisposable.Dispose() => _pooledObject?.Free(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.PooledObjects { [NonCopyable] internal readonly struct PooledDisposer<TPoolable> : IDisposable where TPoolable : class, IPooled { private readonly TPoolable _pooledObject; public PooledDisposer(TPoolable instance) => _pooledObject = instance; void IDisposable.Dispose() => _pooledObject?.Free(); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Workspace/Core/Extensions/ITypeInferenceServiceExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ITypeInferenceServiceExtensions { public static ImmutableArray<ITypeSymbol> InferTypes(this ITypeInferenceService service, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => service.InferTypes(semanticModel, expression, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<ITypeSymbol> InferTypes(this ITypeInferenceService service, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => service.InferTypes(semanticModel, position, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(this ITypeInferenceService service, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => service.GetTypeInferenceInfo(semanticModel, position, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(this ITypeInferenceService service, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => service.GetTypeInferenceInfo(semanticModel, expression, nameOpt: null, cancellationToken: cancellationToken); public static INamedTypeSymbol? InferDelegateType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, expression, cancellationToken); return GetFirstDelegateType(semanticModel, types); } public static INamedTypeSymbol? InferDelegateType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, position, cancellationToken); return GetFirstDelegateType(semanticModel, types); } private static INamedTypeSymbol? GetFirstDelegateType(SemanticModel semanticModel, ImmutableArray<ITypeSymbol> types) { var delegateTypes = types.Select(t => t.GetDelegateType(semanticModel.Compilation)); return delegateTypes.WhereNotNull().FirstOrDefault(); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, bool objectAsDefault, CancellationToken cancellationToken) { return InferType( typeInferenceService, semanticModel, expression, objectAsDefault, name: null, cancellationToken: cancellationToken); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, bool objectAsDefault, string? name, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, expression, name, cancellationToken); if (types.Length == 0) { return objectAsDefault ? semanticModel.Compilation.ObjectType : null; } return types.First(); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, bool objectAsDefault, CancellationToken cancellationToken) { return InferType( typeInferenceService, semanticModel, position, objectAsDefault, name: null, cancellationToken: cancellationToken); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, bool objectAsDefault, string? name, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, position, name, cancellationToken); if (types.Length == 0) { return objectAsDefault ? semanticModel.Compilation.ObjectType : null; } return types.FirstOrDefault(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ITypeInferenceServiceExtensions { public static ImmutableArray<ITypeSymbol> InferTypes(this ITypeInferenceService service, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => service.InferTypes(semanticModel, expression, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<ITypeSymbol> InferTypes(this ITypeInferenceService service, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => service.InferTypes(semanticModel, position, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(this ITypeInferenceService service, SemanticModel semanticModel, int position, CancellationToken cancellationToken) => service.GetTypeInferenceInfo(semanticModel, position, nameOpt: null, cancellationToken: cancellationToken); public static ImmutableArray<TypeInferenceInfo> GetTypeInferenceInfo(this ITypeInferenceService service, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) => service.GetTypeInferenceInfo(semanticModel, expression, nameOpt: null, cancellationToken: cancellationToken); public static INamedTypeSymbol? InferDelegateType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, expression, cancellationToken); return GetFirstDelegateType(semanticModel, types); } public static INamedTypeSymbol? InferDelegateType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, position, cancellationToken); return GetFirstDelegateType(semanticModel, types); } private static INamedTypeSymbol? GetFirstDelegateType(SemanticModel semanticModel, ImmutableArray<ITypeSymbol> types) { var delegateTypes = types.Select(t => t.GetDelegateType(semanticModel.Compilation)); return delegateTypes.WhereNotNull().FirstOrDefault(); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, bool objectAsDefault, CancellationToken cancellationToken) { return InferType( typeInferenceService, semanticModel, expression, objectAsDefault, name: null, cancellationToken: cancellationToken); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, SyntaxNode expression, bool objectAsDefault, string? name, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, expression, name, cancellationToken); if (types.Length == 0) { return objectAsDefault ? semanticModel.Compilation.ObjectType : null; } return types.First(); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, bool objectAsDefault, CancellationToken cancellationToken) { return InferType( typeInferenceService, semanticModel, position, objectAsDefault, name: null, cancellationToken: cancellationToken); } public static ITypeSymbol? InferType( this ITypeInferenceService typeInferenceService, SemanticModel semanticModel, int position, bool objectAsDefault, string? name, CancellationToken cancellationToken) { var types = typeInferenceService.InferTypes(semanticModel, position, name, cancellationToken); if (types.Length == 0) { return objectAsDefault ? semanticModel.Compilation.ObjectType : null; } return types.FirstOrDefault(); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/GoToDefinition/GoToDefinitionHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal static class GoToDefinitionHelpers { public static async Task<ImmutableArray<DefinitionItem>> GetDefinitionsAsync( ISymbol symbol, Solution solution, bool thirdPartyNavigationAllowed, CancellationToken cancellationToken) { var alias = symbol as IAliasSymbol; if (alias != null) { if (alias.Target is INamespaceSymbol ns && ns.IsGlobalNamespace) { return ImmutableArray.Create<DefinitionItem>(); } } // VB global import aliases have a synthesized SyntaxTree. // We can't go to the definition of the alias, so use the target type. if (alias != null) { var sourceLocations = NavigableItemFactory.GetPreferredSourceLocations( solution, symbol, cancellationToken); if (sourceLocations.All(l => solution.GetDocument(l.SourceTree) == null)) { symbol = alias.Target; } } var definition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); symbol = definition ?? symbol; // If it is a partial method declaration with no body, choose to go to the implementation // that has a method body. if (symbol is IMethodSymbol method) { symbol = method.PartialImplementationPart ?? symbol; } using var definitionsDisposer = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); // Going to a symbol may end up actually showing the symbol in the Find-Usages window. // This happens when there is more than one location for the symbol (i.e. for partial // symbols) and we don't know the best place to take you to. // // The FindUsages window supports showing the classified text for an item. It does this // in two ways. Either the item can pass along its classified text (and the window will // defer to that), or the item will have no classified text, and the window will compute // it in the BG. // // Passing along the classified information is valuable for OOP scenarios where we want // all that expensive computation done on the OOP side and not in the VS side. // // However, Go To Definition is all in-process, and is also synchronous. So we do not // want to fetch the classifications here. It slows down the command and leads to a // measurable delay in our perf tests. // // So, if we only have a single location to go to, this does no unnecessary work. And, // if we do have multiple locations to show, it will just be done in the BG, unblocking // this command thread so it can return the user faster. var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (thirdPartyNavigationAllowed) { var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>(); if (factory != null) { var thirdPartyItem = await factory.GetThirdPartyDefinitionItemAsync(solution, definitionItem, cancellationToken).ConfigureAwait(false); definitions.AddIfNotNull(thirdPartyItem); } } definitions.Add(definitionItem); return definitions.ToImmutable(); } public static bool TryGoToDefinition( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { return threadingContext.JoinableTaskFactory.Run( () => TryGoToDefinitionAsync(symbol, solution, threadingContext, streamingPresenter, cancellationToken, thirdPartyNavigationAllowed)); } public static async Task<bool> TryGoToDefinitionAsync( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { var title = string.Format(EditorFeaturesResources._0_declarations, FindUsagesHelpers.GetDisplayName(symbol)); var definitions = await GetDefinitionsAsync(symbol, solution, thirdPartyNavigationAllowed, cancellationToken).ConfigureAwait(false); return await streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToDefinition { internal static class GoToDefinitionHelpers { public static async Task<ImmutableArray<DefinitionItem>> GetDefinitionsAsync( ISymbol symbol, Solution solution, bool thirdPartyNavigationAllowed, CancellationToken cancellationToken) { var alias = symbol as IAliasSymbol; if (alias != null) { if (alias.Target is INamespaceSymbol ns && ns.IsGlobalNamespace) { return ImmutableArray.Create<DefinitionItem>(); } } // VB global import aliases have a synthesized SyntaxTree. // We can't go to the definition of the alias, so use the target type. if (alias != null) { var sourceLocations = NavigableItemFactory.GetPreferredSourceLocations( solution, symbol, cancellationToken); if (sourceLocations.All(l => solution.GetDocument(l.SourceTree) == null)) { symbol = alias.Target; } } var definition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); symbol = definition ?? symbol; // If it is a partial method declaration with no body, choose to go to the implementation // that has a method body. if (symbol is IMethodSymbol method) { symbol = method.PartialImplementationPart ?? symbol; } using var definitionsDisposer = ArrayBuilder<DefinitionItem>.GetInstance(out var definitions); // Going to a symbol may end up actually showing the symbol in the Find-Usages window. // This happens when there is more than one location for the symbol (i.e. for partial // symbols) and we don't know the best place to take you to. // // The FindUsages window supports showing the classified text for an item. It does this // in two ways. Either the item can pass along its classified text (and the window will // defer to that), or the item will have no classified text, and the window will compute // it in the BG. // // Passing along the classified information is valuable for OOP scenarios where we want // all that expensive computation done on the OOP side and not in the VS side. // // However, Go To Definition is all in-process, and is also synchronous. So we do not // want to fetch the classifications here. It slows down the command and leads to a // measurable delay in our perf tests. // // So, if we only have a single location to go to, this does no unnecessary work. And, // if we do have multiple locations to show, it will just be done in the BG, unblocking // this command thread so it can return the user faster. var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (thirdPartyNavigationAllowed) { var factory = solution.Workspace.Services.GetService<IDefinitionsAndReferencesFactory>(); if (factory != null) { var thirdPartyItem = await factory.GetThirdPartyDefinitionItemAsync(solution, definitionItem, cancellationToken).ConfigureAwait(false); definitions.AddIfNotNull(thirdPartyItem); } } definitions.Add(definitionItem); return definitions.ToImmutable(); } public static bool TryGoToDefinition( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { return threadingContext.JoinableTaskFactory.Run( () => TryGoToDefinitionAsync(symbol, solution, threadingContext, streamingPresenter, cancellationToken, thirdPartyNavigationAllowed)); } public static async Task<bool> TryGoToDefinitionAsync( ISymbol symbol, Solution solution, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true) { var title = string.Format(EditorFeaturesResources._0_declarations, FindUsagesHelpers.GetDisplayName(symbol)); var definitions = await GetDefinitionsAsync(symbol, solution, thirdPartyNavigationAllowed, cancellationToken).ConfigureAwait(false); return await streamingPresenter.TryNavigateToOrPresentItemsAsync( threadingContext, solution.Workspace, title, definitions, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/ClassKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 ClassKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyKeywordAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRecord() { await VerifyKeywordAsync( @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttributeFileScopedNamespace() { await VerifyKeywordAsync( @"namespace NS; [Attr] $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 ClassKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task 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 TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyKeywordAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRecord() { await VerifyKeywordAsync( @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttributeFileScopedNamespace() { await VerifyKeywordAsync( @"namespace NS; [Attr] $$"); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/ProjectEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; using System.Threading.Tasks; namespace BuildBoss { /// <summary> /// All of the project entry contained in a solution file. /// </summary> internal struct ProjectEntry { internal string RelativeFilePath { get; } internal string Name { get; } internal Guid ProjectGuid { get; } internal Guid TypeGuid { get; } internal bool IsFolder => TypeGuid == ProjectEntryUtil.FolderProjectType; internal ProjectFileType ProjectType => ProjectEntryUtil.GetProjectFileType(RelativeFilePath); internal ProjectEntry( string relativeFilePath, string name, Guid projectGuid, Guid typeGuid) { RelativeFilePath = relativeFilePath; Name = name; ProjectGuid = projectGuid; TypeGuid = typeGuid; } public override string ToString() => Name; } internal static class ProjectEntryUtil { internal static readonly Guid FolderProjectType = new Guid("2150E333-8FDC-42A3-9474-1A3956D46DE8"); internal static readonly Guid VsixProjectType = new Guid("82B43B9B-A64C-4715-B499-D71E9CA2BD60"); internal static readonly Guid SharedProject = new Guid("D954291E-2A0B-460D-934E-DC6B0785DB48"); internal static readonly Guid ManagedProjectSystemCSharp = new Guid("9A19103F-16F7-4668-BE54-9A1E7A4F7556"); internal static readonly Guid ManagedProjectSystemVisualBasic = new Guid("778DAE3C-4631-46EA-AA77-85C1314464D9"); internal static ProjectFileType GetProjectFileType(string path) { switch (Path.GetExtension(path)) { case ".csproj": return ProjectFileType.CSharp; case ".vbproj": return ProjectFileType.Basic; case ".shproj": return ProjectFileType.Shared; case ".proj": return ProjectFileType.Tool; default: return ProjectFileType.Unknown; } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/CvtRes.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using System.Diagnostics; using BYTE = System.Byte; using DWORD = System.UInt32; using WCHAR = System.Char; using WORD = System.UInt16; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class RESOURCE { internal RESOURCE_STRING? pstringType; internal RESOURCE_STRING? pstringName; internal DWORD DataSize; // size of data without header internal DWORD HeaderSize; // Length of the header // [Ordinal or Name TYPE] // [Ordinal or Name NAME] internal DWORD DataVersion; // version of data struct internal WORD MemoryFlags; // state of the resource internal WORD LanguageId; // Unicode support for NLS internal DWORD Version; // Version of the resource data internal DWORD Characteristics; // Characteristics of the data internal byte[]? data; //data }; internal class RESOURCE_STRING { internal WORD Ordinal; internal string? theString; }; /// <summary> /// Parses .RES a file into its constituent resource elements. /// Mostly translated from cvtres.cpp. /// </summary> internal class CvtResFile { private const WORD RT_DLGINCLUDE = 17; internal static List<RESOURCE> ReadResFile(Stream stream) { var reader = new BinaryReader(stream, Encoding.Unicode); var resourceNames = new List<RESOURCE>(); var startPos = stream.Position; var initial32Bits = reader.ReadUInt32(); //RC.EXE output starts with a resource that contains no data. if (initial32Bits != 0) throw new ResourceException("Stream does not begin with a null resource and is not in .RES format."); stream.Position = startPos; // Build up Type and Name directories while (stream.Position < stream.Length) { // Get the sizes from the file var cbData = reader.ReadUInt32(); var cbHdr = reader.ReadUInt32(); if (cbHdr < 2 * sizeof(DWORD)) { throw new ResourceException(String.Format("Resource header beginning at offset 0x{0:x} is malformed.", stream.Position - 8)); //ErrorPrint(ERR_FILECORRUPT, szFilename); } // Discard null resource if (cbData == 0) { stream.Position += cbHdr - 2 * sizeof(DWORD); continue; } var pAdditional = new RESOURCE() { HeaderSize = cbHdr, DataSize = cbData }; // Read the TYPE and NAME pAdditional.pstringType = ReadStringOrID(reader); pAdditional.pstringName = ReadStringOrID(reader); //round up to dword boundary. stream.Position = (stream.Position + 3) & ~3; // Read the rest of the header pAdditional.DataVersion = reader.ReadUInt32(); pAdditional.MemoryFlags = reader.ReadUInt16(); pAdditional.LanguageId = reader.ReadUInt16(); pAdditional.Version = reader.ReadUInt32(); pAdditional.Characteristics = reader.ReadUInt32(); pAdditional.data = new byte[pAdditional.DataSize]; reader.Read(pAdditional.data, 0, pAdditional.data.Length); stream.Position = (stream.Position + 3) & ~3; if (pAdditional.pstringType.theString == null && (pAdditional.pstringType.Ordinal == (WORD)RT_DLGINCLUDE)) { // Ignore DLGINCLUDE resources continue; } resourceNames.Add(pAdditional); } return resourceNames; } private static RESOURCE_STRING ReadStringOrID(BinaryReader fhIn) { // Reads a String structure from fhIn // If the first word is 0xFFFF then this is an ID // return the ID instead RESOURCE_STRING pstring = new RESOURCE_STRING(); WCHAR firstWord = fhIn.ReadChar(); if (firstWord == 0xFFFF) { // An ID pstring.Ordinal = fhIn.ReadUInt16(); } else { // A string pstring.Ordinal = 0xFFFF; //keep reading until null reached. StringBuilder sb = new StringBuilder(); WCHAR curChar = firstWord; do { sb.Append(curChar); curChar = fhIn.ReadChar(); } while (curChar != 0); pstring.theString = sb.ToString(); } return (pstring); } } internal static class COFFResourceReader { private static void ConfirmSectionValues(SectionHeader hdr, long fileSize) { if ((long)hdr.PointerToRawData + hdr.SizeOfRawData > fileSize) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSectionSize); } internal static Microsoft.Cci.ResourceSection ReadWin32ResourcesFromCOFF(Stream stream) { var peHeaders = new PEHeaders(stream); var rsrc1 = new SectionHeader(); var rsrc2 = new SectionHeader(); int foundCount = 0; foreach (var sectionHeader in peHeaders.SectionHeaders) { if (sectionHeader.Name == ".rsrc$01") { rsrc1 = sectionHeader; foundCount++; } else if (sectionHeader.Name == ".rsrc$02") { rsrc2 = sectionHeader; foundCount++; } } if (foundCount != 2) throw new ResourceException(CodeAnalysisResources.CoffResourceMissingSection); ConfirmSectionValues(rsrc1, stream.Length); ConfirmSectionValues(rsrc2, stream.Length); //This will be the final resource section bytes without a header. It contains the concatenation //of .rsrc$02 on to the end of .rsrc$01. var imageResourceSectionBytes = new byte[checked(rsrc1.SizeOfRawData + rsrc2.SizeOfRawData)]; stream.Seek(rsrc1.PointerToRawData, SeekOrigin.Begin); stream.TryReadAll(imageResourceSectionBytes, 0, rsrc1.SizeOfRawData); // ConfirmSectionValues ensured that data are available stream.Seek(rsrc2.PointerToRawData, SeekOrigin.Begin); stream.TryReadAll(imageResourceSectionBytes, rsrc1.SizeOfRawData, rsrc2.SizeOfRawData); // ConfirmSectionValues ensured that data are available const int SizeOfRelocationEntry = 10; try { var relocLastAddress = checked(rsrc1.PointerToRelocations + (rsrc1.NumberOfRelocations * SizeOfRelocationEntry)); if (relocLastAddress > stream.Length) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); } catch (OverflowException) { throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); } //.rsrc$01 contains the directory tree. .rsrc$02 contains the raw resource data. //.rsrc$01 has references to spots in .rsrc$02. Those spots are expressed as relocations. //These will need to be fixed up when the RVA of the .rsrc section in the final image is known. var relocationOffsets = new uint[rsrc1.NumberOfRelocations]; //offsets into .rsrc$01 var relocationSymbolIndices = new uint[rsrc1.NumberOfRelocations]; var reader = new BinaryReader(stream, Encoding.Unicode); stream.Position = rsrc1.PointerToRelocations; for (int i = 0; i < rsrc1.NumberOfRelocations; i++) { relocationOffsets[i] = reader.ReadUInt32(); //What is being read and stored is the reloc's "Value" //This is the symbol's index. relocationSymbolIndices[i] = reader.ReadUInt32(); reader.ReadUInt16(); //we do nothing with the "Type" } //now that symbol indices are gathered, begin indexing the symbols stream.Position = peHeaders.CoffHeader.PointerToSymbolTable; const uint ImageSizeOfSymbol = 18; try { var lastSymAddress = checked(peHeaders.CoffHeader.PointerToSymbolTable + peHeaders.CoffHeader.NumberOfSymbols * ImageSizeOfSymbol); if (lastSymAddress > stream.Length) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); } catch (OverflowException) { throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); } var outputStream = new MemoryStream(imageResourceSectionBytes); var writer = new BinaryWriter(outputStream); //encoding shouldn't matter. There are no strings being written. for (int i = 0; i < relocationSymbolIndices.Length; i++) { if (relocationSymbolIndices[i] > peHeaders.CoffHeader.NumberOfSymbols) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); var offsetOfSymbol = peHeaders.CoffHeader.PointerToSymbolTable + relocationSymbolIndices[i] * ImageSizeOfSymbol; stream.Position = offsetOfSymbol; stream.Position += 8; //skip over symbol name var symValue = reader.ReadUInt32(); var symSection = reader.ReadInt16(); var symType = reader.ReadUInt16(); //ignore the rest of the fields. const ushort IMAGE_SYM_TYPE_NULL = 0x0000; if (symType != IMAGE_SYM_TYPE_NULL || symSection != 3) //3rd section is .rsrc$02 throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); //perform relocation. We are concatenating the contents of .rsrc$02 (the raw resource data) //on to the end of .rsrc$01 (the directory tree) to yield the final resource section for the image. //The directory tree has references into the raw resource data. These references are expressed //in the final image as file positions, not positions relative to the beginning of the section. //First make the resources be relative to the beginning of the section by adding the size //of .rsrc$01 to them. They will ultimately need the RVA of the final image resource section added //to them. We don't know that yet. That is why the array of offsets is preserved. outputStream.Position = relocationOffsets[i]; writer.Write((uint)(symValue + rsrc1.SizeOfRawData)); } return new Cci.ResourceSection(imageResourceSectionBytes, relocationOffsets); } } internal static class Win32ResourceConversions { private struct ICONDIRENTRY { internal BYTE bWidth; internal BYTE bHeight; internal BYTE bColorCount; internal BYTE bReserved; internal WORD wPlanes; internal WORD wBitCount; internal DWORD dwBytesInRes; internal DWORD dwImageOffset; }; internal static void AppendIconToResourceStream(Stream resStream, Stream iconStream) { var iconReader = new BinaryReader(iconStream); //read magic reserved WORD var reserved = iconReader.ReadUInt16(); if (reserved != 0) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var type = iconReader.ReadUInt16(); if (type != 1) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var count = iconReader.ReadUInt16(); if (count == 0) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var iconDirEntries = new ICONDIRENTRY[count]; for (ushort i = 0; i < count; i++) { // Read the Icon header iconDirEntries[i].bWidth = iconReader.ReadByte(); iconDirEntries[i].bHeight = iconReader.ReadByte(); iconDirEntries[i].bColorCount = iconReader.ReadByte(); iconDirEntries[i].bReserved = iconReader.ReadByte(); iconDirEntries[i].wPlanes = iconReader.ReadUInt16(); iconDirEntries[i].wBitCount = iconReader.ReadUInt16(); iconDirEntries[i].dwBytesInRes = iconReader.ReadUInt32(); iconDirEntries[i].dwImageOffset = iconReader.ReadUInt32(); } // Because Icon files don't seem to record the actual w and BitCount in // the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning // of the data here: //EDMAURER: PNG compressed icons must be treated differently. Do what has always //been done for uncompressed icons. Assume modern, compressed icons set the //ICONDIRENTRY fields correctly. //if (*(DWORD*)icoBuffer == sizeof(BITMAPINFOHEADER)) //{ // grp[i].Planes = ((BITMAPINFOHEADER*)icoBuffer)->biPlanes; // grp[i].BitCount = ((BITMAPINFOHEADER*)icoBuffer)->biBitCount; //} for (ushort i = 0; i < count; i++) { iconStream.Position = iconDirEntries[i].dwImageOffset; if (iconReader.ReadUInt32() == 40) { iconStream.Position += 8; iconDirEntries[i].wPlanes = iconReader.ReadUInt16(); iconDirEntries[i].wBitCount = iconReader.ReadUInt16(); } } //read everything and no exceptions. time to write. var resWriter = new BinaryWriter(resStream); //write all of the icon images as individual resources, then follow up with //a resource that groups them. const WORD RT_ICON = 3; for (ushort i = 0; i < count; i++) { /* write resource header. struct RESOURCEHEADER { DWORD DataSize; DWORD HeaderSize; WORD Magic1; WORD Type; WORD Magic2; WORD Name; DWORD DataVersion; WORD MemoryFlags; WORD LanguageId; DWORD Version; DWORD Characteristics; }; */ resStream.Position = (resStream.Position + 3) & ~3; //headers begin on 4-byte boundaries. resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes); resWriter.Write((DWORD)0x00000020); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)RT_ICON); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)(i + 1)); //EDMAURER this is not general. Implies you can only append one icon to the resources. //This icon ID would seem to be global among all of the icons not just this group. //Zero appears to not be an acceptable ID. Note that this ID is referred to below. resWriter.Write((DWORD)0x00000000); resWriter.Write((WORD)0x1010); resWriter.Write((WORD)0x0000); resWriter.Write((DWORD)0x00000000); resWriter.Write((DWORD)0x00000000); //write the data. iconStream.Position = iconDirEntries[i].dwImageOffset; resWriter.Write(iconReader.ReadBytes(checked((int)iconDirEntries[i].dwBytesInRes))); } /* struct ICONDIR { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource Type (1 for icons) WORD idCount; // How many images? ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em) }/ struct ICONRESDIR { BYTE Width; // = ICONDIRENTRY.bWidth; BYTE Height; // = ICONDIRENTRY.bHeight; BYTE ColorCount; // = ICONDIRENTRY.bColorCount; BYTE reserved; // = ICONDIRENTRY.bReserved; WORD Planes; // = ICONDIRENTRY.wPlanes; WORD BitCount; // = ICONDIRENTRY.wBitCount; DWORD BytesInRes; // = ICONDIRENTRY.dwBytesInRes; WORD IconId; // = RESOURCEHEADER.Name }; */ const WORD RT_GROUP_ICON = RT_ICON + 11; resStream.Position = (resStream.Position + 3) & ~3; //align 4-byte boundary //write the icon group. first a RESOURCEHEADER. the data is the ICONDIR resWriter.Write((DWORD)(3 * sizeof(WORD) + count * /*sizeof(ICONRESDIR)*/ 14)); resWriter.Write((DWORD)0x00000020); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)RT_GROUP_ICON); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)0x7F00); //IDI_APPLICATION resWriter.Write((DWORD)0x00000000); resWriter.Write((WORD)0x1030); resWriter.Write((WORD)0x0000); resWriter.Write((DWORD)0x00000000); resWriter.Write((DWORD)0x00000000); //the ICONDIR resWriter.Write((WORD)0x0000); resWriter.Write((WORD)0x0001); resWriter.Write((WORD)count); for (ushort i = 0; i < count; i++) { resWriter.Write((BYTE)iconDirEntries[i].bWidth); resWriter.Write((BYTE)iconDirEntries[i].bHeight); resWriter.Write((BYTE)iconDirEntries[i].bColorCount); resWriter.Write((BYTE)iconDirEntries[i].bReserved); resWriter.Write((WORD)iconDirEntries[i].wPlanes); resWriter.Write((WORD)iconDirEntries[i].wBitCount); resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes); resWriter.Write((WORD)(i + 1)); //ID } } /* * Dev10 alink had the following fallback behavior. private uint[] FileVersion { get { if (fileVersionContents != null) return fileVersionContents; else { System.Diagnostics.Debug.Assert(assemblyVersionContents != null); return assemblyVersionContents; } } } private uint[] ProductVersion { get { if (productVersionContents != null) return productVersionContents; else return this.FileVersion; } } */ internal static void AppendVersionToResourceStream(Stream resStream, bool isDll, string fileVersion, //should be [major.minor.build.rev] but doesn't have to be string originalFileName, string internalName, string productVersion, //4 ints Version assemblyVersion, //individual values must be smaller than 65535 string fileDescription = " ", //the old compiler put blank here if nothing was user-supplied string legalCopyright = " ", //the old compiler put blank here if nothing was user-supplied string? legalTrademarks = null, string? productName = null, string? comments = null, string? companyName = null) { var resWriter = new BinaryWriter(resStream, Encoding.Unicode); resStream.Position = (resStream.Position + 3) & ~3; const DWORD RT_VERSION = 16; var ver = new VersionResourceSerializer(isDll, comments, companyName, fileDescription, fileVersion, internalName, legalCopyright, legalTrademarks, originalFileName, productName, productVersion, assemblyVersion); var startPos = resStream.Position; var dataSize = ver.GetDataSize(); const int headerSize = 0x20; resWriter.Write((DWORD)dataSize); //data size resWriter.Write((DWORD)headerSize); //header size resWriter.Write((WORD)0xFFFF); //identifies type as ordinal. resWriter.Write((WORD)RT_VERSION); //type resWriter.Write((WORD)0xFFFF); //identifies name as ordinal. resWriter.Write((WORD)0x0001); //only ever 1 ver resource (what Dev10 does) resWriter.Write((DWORD)0x00000000); //data version resWriter.Write((WORD)0x0030); //memory flags (this is what the Dev10 compiler uses) resWriter.Write((WORD)0x0000); //languageId resWriter.Write((DWORD)0x00000000); //version resWriter.Write((DWORD)0x00000000); //characteristics ver.WriteVerResource(resWriter); System.Diagnostics.Debug.Assert(resStream.Position - startPos == dataSize + headerSize); } internal static void AppendManifestToResourceStream(Stream resStream, Stream manifestStream, bool isDll) { resStream.Position = (resStream.Position + 3) & ~3; const WORD RT_MANIFEST = 24; var resWriter = new BinaryWriter(resStream); resWriter.Write((DWORD)(manifestStream.Length)); //data size resWriter.Write((DWORD)0x00000020); //header size resWriter.Write((WORD)0xFFFF); //identifies type as ordinal. resWriter.Write((WORD)RT_MANIFEST); //type resWriter.Write((WORD)0xFFFF); //identifies name as ordinal. resWriter.Write((WORD)((isDll) ? 0x0002 : 0x0001)); //EDMAURER executables are named "1", DLLs "2" resWriter.Write((DWORD)0x00000000); //data version resWriter.Write((WORD)0x1030); //memory flags resWriter.Write((WORD)0x0000); //languageId resWriter.Write((DWORD)0x00000000); //version resWriter.Write((DWORD)0x00000000); //characteristics manifestStream.CopyTo(resStream); } private class VersionResourceSerializer { private readonly string? _commentsContents; private readonly string? _companyNameContents; private readonly string _fileDescriptionContents; private readonly string _fileVersionContents; private readonly string _internalNameContents; private readonly string _legalCopyrightContents; private readonly string? _legalTrademarksContents; private readonly string _originalFileNameContents; private readonly string? _productNameContents; private readonly string _productVersionContents; private readonly Version _assemblyVersionContents; private const string vsVersionInfoKey = "VS_VERSION_INFO"; private const string varFileInfoKey = "VarFileInfo"; private const string translationKey = "Translation"; private const string stringFileInfoKey = "StringFileInfo"; private readonly string _langIdAndCodePageKey; //should be 8 characters private const DWORD CP_WINUNICODE = 1200; private const ushort sizeVS_FIXEDFILEINFO = sizeof(DWORD) * 13; private readonly bool _isDll; internal VersionResourceSerializer(bool isDll, string? comments, string? companyName, string fileDescription, string fileVersion, string internalName, string legalCopyright, string? legalTrademark, string originalFileName, string? productName, string productVersion, Version assemblyVersion) { _isDll = isDll; _commentsContents = comments; _companyNameContents = companyName; _fileDescriptionContents = fileDescription; _fileVersionContents = fileVersion; _internalNameContents = internalName; _legalCopyrightContents = legalCopyright; _legalTrademarksContents = legalTrademark; _originalFileNameContents = originalFileName; _productNameContents = productName; _productVersionContents = productVersion; _assemblyVersionContents = assemblyVersion; _langIdAndCodePageKey = System.String.Format("{0:x4}{1:x4}", 0 /*langId*/, CP_WINUNICODE /*codepage*/); } private const uint VFT_APP = 0x00000001; private const uint VFT_DLL = 0x00000002; private IEnumerable<KeyValuePair<string, string>> GetVerStrings() { if (_commentsContents != null) yield return new KeyValuePair<string, string>("Comments", _commentsContents); if (_companyNameContents != null) yield return new KeyValuePair<string, string>("CompanyName", _companyNameContents); if (_fileDescriptionContents != null) yield return new KeyValuePair<string, string>("FileDescription", _fileDescriptionContents); yield return new KeyValuePair<string, string>("FileVersion", _fileVersionContents); if (_internalNameContents != null) yield return new KeyValuePair<string, string>("InternalName", _internalNameContents); if (_legalCopyrightContents != null) yield return new KeyValuePair<string, string>("LegalCopyright", _legalCopyrightContents); if (_legalTrademarksContents != null) yield return new KeyValuePair<string, string>("LegalTrademarks", _legalTrademarksContents); if (_originalFileNameContents != null) yield return new KeyValuePair<string, string>("OriginalFilename", _originalFileNameContents); if (_productNameContents != null) yield return new KeyValuePair<string, string>("ProductName", _productNameContents); yield return new KeyValuePair<string, string>("ProductVersion", _productVersionContents); if (_assemblyVersionContents != null) yield return new KeyValuePair<string, string>("Assembly Version", _assemblyVersionContents.ToString()); } private uint FileType { get { return (_isDll) ? VFT_DLL : VFT_APP; } } private void WriteVSFixedFileInfo(BinaryWriter writer) { //There's nothing guaranteeing that these are n.n.n.n format. //The documentation says that if they're not that format the behavior is undefined. Version fileVersion; VersionHelper.TryParse(_fileVersionContents, version: out fileVersion); Version productVersion; VersionHelper.TryParse(_productVersionContents, version: out productVersion); writer.Write((DWORD)0xFEEF04BD); writer.Write((DWORD)0x00010000); writer.Write((DWORD)((uint)fileVersion.Major << 16) | (uint)fileVersion.Minor); writer.Write((DWORD)((uint)fileVersion.Build << 16) | (uint)fileVersion.Revision); writer.Write((DWORD)((uint)productVersion.Major << 16) | (uint)productVersion.Minor); writer.Write((DWORD)((uint)productVersion.Build << 16) | (uint)productVersion.Revision); writer.Write((DWORD)0x0000003F); //VS_FFI_FILEFLAGSMASK (EDMAURER) really? all these bits are valid? writer.Write((DWORD)0); //file flags writer.Write((DWORD)0x00000004); //VOS__WINDOWS32 writer.Write((DWORD)this.FileType); writer.Write((DWORD)0); //file subtype writer.Write((DWORD)0); //date most sig writer.Write((DWORD)0); //date least sig } /// <summary> /// Assume that 3 WORDs preceded this string and that they began 32-bit aligned. /// Given the string length compute the number of bytes that should be written to end /// the buffer on a 32-bit boundary</summary> /// <param name="cb"></param> /// <returns></returns> private static int PadKeyLen(int cb) { //add previously written 3 WORDS, round up, then subtract the 3 WORDS. return PadToDword(cb + 3 * sizeof(WORD)) - 3 * sizeof(WORD); } /// <summary> /// assuming the length of bytes submitted began on a 32-bit boundary, /// round up this length as necessary so that it ends at a 32-bit boundary. /// </summary> /// <param name="cb"></param> /// <returns></returns> private static int PadToDword(int cb) { return (cb + 3) & ~3; } private const int HDRSIZE = 3 * sizeof(ushort); private static ushort SizeofVerString(string lpszKey, string lpszValue) { int cbKey, cbValue; cbKey = (lpszKey.Length + 1) * 2; // Make room for the NULL cbValue = (lpszValue.Length + 1) * 2; return checked((ushort)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary cbValue + // value HDRSIZE)); // block header. } private static void WriteVersionString(KeyValuePair<string, string> keyValuePair, BinaryWriter writer) { RoslynDebug.Assert(keyValuePair.Value != null); ushort cbBlock = SizeofVerString(keyValuePair.Key, keyValuePair.Value); int cbKey = (keyValuePair.Key.Length + 1) * 2; // includes terminating NUL int cbVal = (keyValuePair.Value.Length + 1) * 2; // includes terminating NUL var startPos = writer.BaseStream.Position; Debug.Assert((startPos & 3) == 0); writer.Write((WORD)cbBlock); writer.Write((WORD)(keyValuePair.Value.Length + 1)); //add 1 for nul writer.Write((WORD)1); writer.Write(keyValuePair.Key.ToCharArray()); writer.Write((WORD)'\0'); writer.Write(new byte[PadKeyLen(cbKey) - cbKey]); Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write(keyValuePair.Value.ToCharArray()); writer.Write((WORD)'\0'); //writer.Write(new byte[PadToDword(cbVal) - cbVal]); System.Diagnostics.Debug.Assert(cbBlock == writer.BaseStream.Position - startPos); } /// <summary> /// compute number of chars needed to end up on a 32-bit boundary assuming that three /// WORDS preceded this string. /// </summary> /// <param name="sz"></param> /// <returns></returns> private static int KEYSIZE(string sz) { return PadKeyLen((sz.Length + 1) * sizeof(WCHAR)) / sizeof(WCHAR); } private static int KEYBYTES(string sz) { return KEYSIZE(sz) * sizeof(WCHAR); } private int GetStringsSize() { int sum = 0; foreach (var verString in GetVerStrings()) { sum = (sum + 3) & ~3; //ensure that each String data structure starts on a 32bit boundary. sum += SizeofVerString(verString.Key, verString.Value); } return sum; } internal int GetDataSize() { int sizeEXEVERRESOURCE = sizeof(WORD) * 3 * 5 + 2 * sizeof(WORD) + //five headers + two words for CP and lang KEYBYTES(vsVersionInfoKey) + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey) + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + sizeVS_FIXEDFILEINFO; return GetStringsSize() + sizeEXEVERRESOURCE; } internal void WriteVerResource(BinaryWriter writer) { /* must be assumed to start on a 32-bit boundary. * * the sub-elements of the VS_VERSIONINFO consist of a header (3 WORDS) a string * and then beginning on the next 32-bit boundary, the elements children struct VS_VERSIONINFO { WORD cbRootBlock; // size of whole resource WORD cbRootValue; // size of VS_FIXEDFILEINFO structure WORD fRootText; // root is text? WCHAR szRootKey[KEYSIZE("VS_VERSION_INFO")]; // Holds "VS_VERSION_INFO" VS_FIXEDFILEINFO vsFixed; // fixed information. WORD cbVarBlock; // size of VarFileInfo block WORD cbVarValue; // always 0 WORD fVarText; // VarFileInfo is text? WCHAR szVarKey[KEYSIZE("VarFileInfo")]; // Holds "VarFileInfo" WORD cbTransBlock; // size of Translation block WORD cbTransValue; // size of Translation value WORD fTransText; // Translation is text? WCHAR szTransKey[KEYSIZE("Translation")]; // Holds "Translation" WORD langid; // language id WORD codepage; // codepage id WORD cbStringBlock; // size of StringFileInfo block WORD cbStringValue; // always 0 WORD fStringText; // StringFileInfo is text? WCHAR szStringKey[KEYSIZE("StringFileInfo")]; // Holds "StringFileInfo" WORD cbLangCpBlock; // size of language/codepage block WORD cbLangCpValue; // always 0 WORD fLangCpText; // LangCp is text? WCHAR szLangCpKey[KEYSIZE("12345678")]; // Holds hex version of language/codepage // followed by strings }; */ var debugPos = writer.BaseStream.Position; var dataSize = GetDataSize(); writer.Write((WORD)dataSize); writer.Write((WORD)sizeVS_FIXEDFILEINFO); writer.Write((WORD)0); writer.Write(vsVersionInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(vsVersionInfoKey) - vsVersionInfoKey.Length * 2]); System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); WriteVSFixedFileInfo(writer); writer.Write((WORD)(sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey))); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(varFileInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(varFileInfoKey) - varFileInfoKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(sizeof(WORD) * 2 + HDRSIZE + KEYBYTES(translationKey))); writer.Write((WORD)(sizeof(WORD) * 2)); writer.Write((WORD)0); writer.Write(translationKey.ToCharArray()); writer.Write(new byte[KEYBYTES(translationKey) - translationKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)0); //langId; MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)) = 0 writer.Write((WORD)CP_WINUNICODE); //codepage; 1200 = CP_WINUNICODE System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(2 * HDRSIZE + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(stringFileInfoKey.ToCharArray()); //actually preceded by 5 WORDS so not consistent with the //assumptions of KEYBYTES, but equivalent. writer.Write(new byte[KEYBYTES(stringFileInfoKey) - stringFileInfoKey.Length * 2]); //padding. System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(HDRSIZE + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(_langIdAndCodePageKey.ToCharArray()); writer.Write(new byte[KEYBYTES(_langIdAndCodePageKey) - _langIdAndCodePageKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == dataSize - GetStringsSize()); debugPos = writer.BaseStream.Position; foreach (var entry in GetVerStrings()) { var writerPos = writer.BaseStream.Position; //write any padding necessary to align the String struct on a 32 bit boundary. writer.Write(new byte[((writerPos + 3) & ~3) - writerPos]); System.Diagnostics.Debug.Assert(entry.Value != null); WriteVersionString(entry, writer); } System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == GetStringsSize()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using System.Diagnostics; using BYTE = System.Byte; using DWORD = System.UInt32; using WCHAR = System.Char; using WORD = System.UInt16; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal class RESOURCE { internal RESOURCE_STRING? pstringType; internal RESOURCE_STRING? pstringName; internal DWORD DataSize; // size of data without header internal DWORD HeaderSize; // Length of the header // [Ordinal or Name TYPE] // [Ordinal or Name NAME] internal DWORD DataVersion; // version of data struct internal WORD MemoryFlags; // state of the resource internal WORD LanguageId; // Unicode support for NLS internal DWORD Version; // Version of the resource data internal DWORD Characteristics; // Characteristics of the data internal byte[]? data; //data }; internal class RESOURCE_STRING { internal WORD Ordinal; internal string? theString; }; /// <summary> /// Parses .RES a file into its constituent resource elements. /// Mostly translated from cvtres.cpp. /// </summary> internal class CvtResFile { private const WORD RT_DLGINCLUDE = 17; internal static List<RESOURCE> ReadResFile(Stream stream) { var reader = new BinaryReader(stream, Encoding.Unicode); var resourceNames = new List<RESOURCE>(); var startPos = stream.Position; var initial32Bits = reader.ReadUInt32(); //RC.EXE output starts with a resource that contains no data. if (initial32Bits != 0) throw new ResourceException("Stream does not begin with a null resource and is not in .RES format."); stream.Position = startPos; // Build up Type and Name directories while (stream.Position < stream.Length) { // Get the sizes from the file var cbData = reader.ReadUInt32(); var cbHdr = reader.ReadUInt32(); if (cbHdr < 2 * sizeof(DWORD)) { throw new ResourceException(String.Format("Resource header beginning at offset 0x{0:x} is malformed.", stream.Position - 8)); //ErrorPrint(ERR_FILECORRUPT, szFilename); } // Discard null resource if (cbData == 0) { stream.Position += cbHdr - 2 * sizeof(DWORD); continue; } var pAdditional = new RESOURCE() { HeaderSize = cbHdr, DataSize = cbData }; // Read the TYPE and NAME pAdditional.pstringType = ReadStringOrID(reader); pAdditional.pstringName = ReadStringOrID(reader); //round up to dword boundary. stream.Position = (stream.Position + 3) & ~3; // Read the rest of the header pAdditional.DataVersion = reader.ReadUInt32(); pAdditional.MemoryFlags = reader.ReadUInt16(); pAdditional.LanguageId = reader.ReadUInt16(); pAdditional.Version = reader.ReadUInt32(); pAdditional.Characteristics = reader.ReadUInt32(); pAdditional.data = new byte[pAdditional.DataSize]; reader.Read(pAdditional.data, 0, pAdditional.data.Length); stream.Position = (stream.Position + 3) & ~3; if (pAdditional.pstringType.theString == null && (pAdditional.pstringType.Ordinal == (WORD)RT_DLGINCLUDE)) { // Ignore DLGINCLUDE resources continue; } resourceNames.Add(pAdditional); } return resourceNames; } private static RESOURCE_STRING ReadStringOrID(BinaryReader fhIn) { // Reads a String structure from fhIn // If the first word is 0xFFFF then this is an ID // return the ID instead RESOURCE_STRING pstring = new RESOURCE_STRING(); WCHAR firstWord = fhIn.ReadChar(); if (firstWord == 0xFFFF) { // An ID pstring.Ordinal = fhIn.ReadUInt16(); } else { // A string pstring.Ordinal = 0xFFFF; //keep reading until null reached. StringBuilder sb = new StringBuilder(); WCHAR curChar = firstWord; do { sb.Append(curChar); curChar = fhIn.ReadChar(); } while (curChar != 0); pstring.theString = sb.ToString(); } return (pstring); } } internal static class COFFResourceReader { private static void ConfirmSectionValues(SectionHeader hdr, long fileSize) { if ((long)hdr.PointerToRawData + hdr.SizeOfRawData > fileSize) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSectionSize); } internal static Microsoft.Cci.ResourceSection ReadWin32ResourcesFromCOFF(Stream stream) { var peHeaders = new PEHeaders(stream); var rsrc1 = new SectionHeader(); var rsrc2 = new SectionHeader(); int foundCount = 0; foreach (var sectionHeader in peHeaders.SectionHeaders) { if (sectionHeader.Name == ".rsrc$01") { rsrc1 = sectionHeader; foundCount++; } else if (sectionHeader.Name == ".rsrc$02") { rsrc2 = sectionHeader; foundCount++; } } if (foundCount != 2) throw new ResourceException(CodeAnalysisResources.CoffResourceMissingSection); ConfirmSectionValues(rsrc1, stream.Length); ConfirmSectionValues(rsrc2, stream.Length); //This will be the final resource section bytes without a header. It contains the concatenation //of .rsrc$02 on to the end of .rsrc$01. var imageResourceSectionBytes = new byte[checked(rsrc1.SizeOfRawData + rsrc2.SizeOfRawData)]; stream.Seek(rsrc1.PointerToRawData, SeekOrigin.Begin); stream.TryReadAll(imageResourceSectionBytes, 0, rsrc1.SizeOfRawData); // ConfirmSectionValues ensured that data are available stream.Seek(rsrc2.PointerToRawData, SeekOrigin.Begin); stream.TryReadAll(imageResourceSectionBytes, rsrc1.SizeOfRawData, rsrc2.SizeOfRawData); // ConfirmSectionValues ensured that data are available const int SizeOfRelocationEntry = 10; try { var relocLastAddress = checked(rsrc1.PointerToRelocations + (rsrc1.NumberOfRelocations * SizeOfRelocationEntry)); if (relocLastAddress > stream.Length) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); } catch (OverflowException) { throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); } //.rsrc$01 contains the directory tree. .rsrc$02 contains the raw resource data. //.rsrc$01 has references to spots in .rsrc$02. Those spots are expressed as relocations. //These will need to be fixed up when the RVA of the .rsrc section in the final image is known. var relocationOffsets = new uint[rsrc1.NumberOfRelocations]; //offsets into .rsrc$01 var relocationSymbolIndices = new uint[rsrc1.NumberOfRelocations]; var reader = new BinaryReader(stream, Encoding.Unicode); stream.Position = rsrc1.PointerToRelocations; for (int i = 0; i < rsrc1.NumberOfRelocations; i++) { relocationOffsets[i] = reader.ReadUInt32(); //What is being read and stored is the reloc's "Value" //This is the symbol's index. relocationSymbolIndices[i] = reader.ReadUInt32(); reader.ReadUInt16(); //we do nothing with the "Type" } //now that symbol indices are gathered, begin indexing the symbols stream.Position = peHeaders.CoffHeader.PointerToSymbolTable; const uint ImageSizeOfSymbol = 18; try { var lastSymAddress = checked(peHeaders.CoffHeader.PointerToSymbolTable + peHeaders.CoffHeader.NumberOfSymbols * ImageSizeOfSymbol); if (lastSymAddress > stream.Length) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); } catch (OverflowException) { throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); } var outputStream = new MemoryStream(imageResourceSectionBytes); var writer = new BinaryWriter(outputStream); //encoding shouldn't matter. There are no strings being written. for (int i = 0; i < relocationSymbolIndices.Length; i++) { if (relocationSymbolIndices[i] > peHeaders.CoffHeader.NumberOfSymbols) throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidRelocation); var offsetOfSymbol = peHeaders.CoffHeader.PointerToSymbolTable + relocationSymbolIndices[i] * ImageSizeOfSymbol; stream.Position = offsetOfSymbol; stream.Position += 8; //skip over symbol name var symValue = reader.ReadUInt32(); var symSection = reader.ReadInt16(); var symType = reader.ReadUInt16(); //ignore the rest of the fields. const ushort IMAGE_SYM_TYPE_NULL = 0x0000; if (symType != IMAGE_SYM_TYPE_NULL || symSection != 3) //3rd section is .rsrc$02 throw new ResourceException(CodeAnalysisResources.CoffResourceInvalidSymbol); //perform relocation. We are concatenating the contents of .rsrc$02 (the raw resource data) //on to the end of .rsrc$01 (the directory tree) to yield the final resource section for the image. //The directory tree has references into the raw resource data. These references are expressed //in the final image as file positions, not positions relative to the beginning of the section. //First make the resources be relative to the beginning of the section by adding the size //of .rsrc$01 to them. They will ultimately need the RVA of the final image resource section added //to them. We don't know that yet. That is why the array of offsets is preserved. outputStream.Position = relocationOffsets[i]; writer.Write((uint)(symValue + rsrc1.SizeOfRawData)); } return new Cci.ResourceSection(imageResourceSectionBytes, relocationOffsets); } } internal static class Win32ResourceConversions { private struct ICONDIRENTRY { internal BYTE bWidth; internal BYTE bHeight; internal BYTE bColorCount; internal BYTE bReserved; internal WORD wPlanes; internal WORD wBitCount; internal DWORD dwBytesInRes; internal DWORD dwImageOffset; }; internal static void AppendIconToResourceStream(Stream resStream, Stream iconStream) { var iconReader = new BinaryReader(iconStream); //read magic reserved WORD var reserved = iconReader.ReadUInt16(); if (reserved != 0) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var type = iconReader.ReadUInt16(); if (type != 1) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var count = iconReader.ReadUInt16(); if (count == 0) throw new ResourceException(CodeAnalysisResources.IconStreamUnexpectedFormat); var iconDirEntries = new ICONDIRENTRY[count]; for (ushort i = 0; i < count; i++) { // Read the Icon header iconDirEntries[i].bWidth = iconReader.ReadByte(); iconDirEntries[i].bHeight = iconReader.ReadByte(); iconDirEntries[i].bColorCount = iconReader.ReadByte(); iconDirEntries[i].bReserved = iconReader.ReadByte(); iconDirEntries[i].wPlanes = iconReader.ReadUInt16(); iconDirEntries[i].wBitCount = iconReader.ReadUInt16(); iconDirEntries[i].dwBytesInRes = iconReader.ReadUInt32(); iconDirEntries[i].dwImageOffset = iconReader.ReadUInt32(); } // Because Icon files don't seem to record the actual w and BitCount in // the ICONDIRENTRY, get the info from the BITMAPINFOHEADER at the beginning // of the data here: //EDMAURER: PNG compressed icons must be treated differently. Do what has always //been done for uncompressed icons. Assume modern, compressed icons set the //ICONDIRENTRY fields correctly. //if (*(DWORD*)icoBuffer == sizeof(BITMAPINFOHEADER)) //{ // grp[i].Planes = ((BITMAPINFOHEADER*)icoBuffer)->biPlanes; // grp[i].BitCount = ((BITMAPINFOHEADER*)icoBuffer)->biBitCount; //} for (ushort i = 0; i < count; i++) { iconStream.Position = iconDirEntries[i].dwImageOffset; if (iconReader.ReadUInt32() == 40) { iconStream.Position += 8; iconDirEntries[i].wPlanes = iconReader.ReadUInt16(); iconDirEntries[i].wBitCount = iconReader.ReadUInt16(); } } //read everything and no exceptions. time to write. var resWriter = new BinaryWriter(resStream); //write all of the icon images as individual resources, then follow up with //a resource that groups them. const WORD RT_ICON = 3; for (ushort i = 0; i < count; i++) { /* write resource header. struct RESOURCEHEADER { DWORD DataSize; DWORD HeaderSize; WORD Magic1; WORD Type; WORD Magic2; WORD Name; DWORD DataVersion; WORD MemoryFlags; WORD LanguageId; DWORD Version; DWORD Characteristics; }; */ resStream.Position = (resStream.Position + 3) & ~3; //headers begin on 4-byte boundaries. resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes); resWriter.Write((DWORD)0x00000020); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)RT_ICON); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)(i + 1)); //EDMAURER this is not general. Implies you can only append one icon to the resources. //This icon ID would seem to be global among all of the icons not just this group. //Zero appears to not be an acceptable ID. Note that this ID is referred to below. resWriter.Write((DWORD)0x00000000); resWriter.Write((WORD)0x1010); resWriter.Write((WORD)0x0000); resWriter.Write((DWORD)0x00000000); resWriter.Write((DWORD)0x00000000); //write the data. iconStream.Position = iconDirEntries[i].dwImageOffset; resWriter.Write(iconReader.ReadBytes(checked((int)iconDirEntries[i].dwBytesInRes))); } /* struct ICONDIR { WORD idReserved; // Reserved (must be 0) WORD idType; // Resource Type (1 for icons) WORD idCount; // How many images? ICONDIRENTRY idEntries[1]; // An entry for each image (idCount of 'em) }/ struct ICONRESDIR { BYTE Width; // = ICONDIRENTRY.bWidth; BYTE Height; // = ICONDIRENTRY.bHeight; BYTE ColorCount; // = ICONDIRENTRY.bColorCount; BYTE reserved; // = ICONDIRENTRY.bReserved; WORD Planes; // = ICONDIRENTRY.wPlanes; WORD BitCount; // = ICONDIRENTRY.wBitCount; DWORD BytesInRes; // = ICONDIRENTRY.dwBytesInRes; WORD IconId; // = RESOURCEHEADER.Name }; */ const WORD RT_GROUP_ICON = RT_ICON + 11; resStream.Position = (resStream.Position + 3) & ~3; //align 4-byte boundary //write the icon group. first a RESOURCEHEADER. the data is the ICONDIR resWriter.Write((DWORD)(3 * sizeof(WORD) + count * /*sizeof(ICONRESDIR)*/ 14)); resWriter.Write((DWORD)0x00000020); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)RT_GROUP_ICON); resWriter.Write((WORD)0xFFFF); resWriter.Write((WORD)0x7F00); //IDI_APPLICATION resWriter.Write((DWORD)0x00000000); resWriter.Write((WORD)0x1030); resWriter.Write((WORD)0x0000); resWriter.Write((DWORD)0x00000000); resWriter.Write((DWORD)0x00000000); //the ICONDIR resWriter.Write((WORD)0x0000); resWriter.Write((WORD)0x0001); resWriter.Write((WORD)count); for (ushort i = 0; i < count; i++) { resWriter.Write((BYTE)iconDirEntries[i].bWidth); resWriter.Write((BYTE)iconDirEntries[i].bHeight); resWriter.Write((BYTE)iconDirEntries[i].bColorCount); resWriter.Write((BYTE)iconDirEntries[i].bReserved); resWriter.Write((WORD)iconDirEntries[i].wPlanes); resWriter.Write((WORD)iconDirEntries[i].wBitCount); resWriter.Write((DWORD)iconDirEntries[i].dwBytesInRes); resWriter.Write((WORD)(i + 1)); //ID } } /* * Dev10 alink had the following fallback behavior. private uint[] FileVersion { get { if (fileVersionContents != null) return fileVersionContents; else { System.Diagnostics.Debug.Assert(assemblyVersionContents != null); return assemblyVersionContents; } } } private uint[] ProductVersion { get { if (productVersionContents != null) return productVersionContents; else return this.FileVersion; } } */ internal static void AppendVersionToResourceStream(Stream resStream, bool isDll, string fileVersion, //should be [major.minor.build.rev] but doesn't have to be string originalFileName, string internalName, string productVersion, //4 ints Version assemblyVersion, //individual values must be smaller than 65535 string fileDescription = " ", //the old compiler put blank here if nothing was user-supplied string legalCopyright = " ", //the old compiler put blank here if nothing was user-supplied string? legalTrademarks = null, string? productName = null, string? comments = null, string? companyName = null) { var resWriter = new BinaryWriter(resStream, Encoding.Unicode); resStream.Position = (resStream.Position + 3) & ~3; const DWORD RT_VERSION = 16; var ver = new VersionResourceSerializer(isDll, comments, companyName, fileDescription, fileVersion, internalName, legalCopyright, legalTrademarks, originalFileName, productName, productVersion, assemblyVersion); var startPos = resStream.Position; var dataSize = ver.GetDataSize(); const int headerSize = 0x20; resWriter.Write((DWORD)dataSize); //data size resWriter.Write((DWORD)headerSize); //header size resWriter.Write((WORD)0xFFFF); //identifies type as ordinal. resWriter.Write((WORD)RT_VERSION); //type resWriter.Write((WORD)0xFFFF); //identifies name as ordinal. resWriter.Write((WORD)0x0001); //only ever 1 ver resource (what Dev10 does) resWriter.Write((DWORD)0x00000000); //data version resWriter.Write((WORD)0x0030); //memory flags (this is what the Dev10 compiler uses) resWriter.Write((WORD)0x0000); //languageId resWriter.Write((DWORD)0x00000000); //version resWriter.Write((DWORD)0x00000000); //characteristics ver.WriteVerResource(resWriter); System.Diagnostics.Debug.Assert(resStream.Position - startPos == dataSize + headerSize); } internal static void AppendManifestToResourceStream(Stream resStream, Stream manifestStream, bool isDll) { resStream.Position = (resStream.Position + 3) & ~3; const WORD RT_MANIFEST = 24; var resWriter = new BinaryWriter(resStream); resWriter.Write((DWORD)(manifestStream.Length)); //data size resWriter.Write((DWORD)0x00000020); //header size resWriter.Write((WORD)0xFFFF); //identifies type as ordinal. resWriter.Write((WORD)RT_MANIFEST); //type resWriter.Write((WORD)0xFFFF); //identifies name as ordinal. resWriter.Write((WORD)((isDll) ? 0x0002 : 0x0001)); //EDMAURER executables are named "1", DLLs "2" resWriter.Write((DWORD)0x00000000); //data version resWriter.Write((WORD)0x1030); //memory flags resWriter.Write((WORD)0x0000); //languageId resWriter.Write((DWORD)0x00000000); //version resWriter.Write((DWORD)0x00000000); //characteristics manifestStream.CopyTo(resStream); } private class VersionResourceSerializer { private readonly string? _commentsContents; private readonly string? _companyNameContents; private readonly string _fileDescriptionContents; private readonly string _fileVersionContents; private readonly string _internalNameContents; private readonly string _legalCopyrightContents; private readonly string? _legalTrademarksContents; private readonly string _originalFileNameContents; private readonly string? _productNameContents; private readonly string _productVersionContents; private readonly Version _assemblyVersionContents; private const string vsVersionInfoKey = "VS_VERSION_INFO"; private const string varFileInfoKey = "VarFileInfo"; private const string translationKey = "Translation"; private const string stringFileInfoKey = "StringFileInfo"; private readonly string _langIdAndCodePageKey; //should be 8 characters private const DWORD CP_WINUNICODE = 1200; private const ushort sizeVS_FIXEDFILEINFO = sizeof(DWORD) * 13; private readonly bool _isDll; internal VersionResourceSerializer(bool isDll, string? comments, string? companyName, string fileDescription, string fileVersion, string internalName, string legalCopyright, string? legalTrademark, string originalFileName, string? productName, string productVersion, Version assemblyVersion) { _isDll = isDll; _commentsContents = comments; _companyNameContents = companyName; _fileDescriptionContents = fileDescription; _fileVersionContents = fileVersion; _internalNameContents = internalName; _legalCopyrightContents = legalCopyright; _legalTrademarksContents = legalTrademark; _originalFileNameContents = originalFileName; _productNameContents = productName; _productVersionContents = productVersion; _assemblyVersionContents = assemblyVersion; _langIdAndCodePageKey = System.String.Format("{0:x4}{1:x4}", 0 /*langId*/, CP_WINUNICODE /*codepage*/); } private const uint VFT_APP = 0x00000001; private const uint VFT_DLL = 0x00000002; private IEnumerable<KeyValuePair<string, string>> GetVerStrings() { if (_commentsContents != null) yield return new KeyValuePair<string, string>("Comments", _commentsContents); if (_companyNameContents != null) yield return new KeyValuePair<string, string>("CompanyName", _companyNameContents); if (_fileDescriptionContents != null) yield return new KeyValuePair<string, string>("FileDescription", _fileDescriptionContents); yield return new KeyValuePair<string, string>("FileVersion", _fileVersionContents); if (_internalNameContents != null) yield return new KeyValuePair<string, string>("InternalName", _internalNameContents); if (_legalCopyrightContents != null) yield return new KeyValuePair<string, string>("LegalCopyright", _legalCopyrightContents); if (_legalTrademarksContents != null) yield return new KeyValuePair<string, string>("LegalTrademarks", _legalTrademarksContents); if (_originalFileNameContents != null) yield return new KeyValuePair<string, string>("OriginalFilename", _originalFileNameContents); if (_productNameContents != null) yield return new KeyValuePair<string, string>("ProductName", _productNameContents); yield return new KeyValuePair<string, string>("ProductVersion", _productVersionContents); if (_assemblyVersionContents != null) yield return new KeyValuePair<string, string>("Assembly Version", _assemblyVersionContents.ToString()); } private uint FileType { get { return (_isDll) ? VFT_DLL : VFT_APP; } } private void WriteVSFixedFileInfo(BinaryWriter writer) { //There's nothing guaranteeing that these are n.n.n.n format. //The documentation says that if they're not that format the behavior is undefined. Version fileVersion; VersionHelper.TryParse(_fileVersionContents, version: out fileVersion); Version productVersion; VersionHelper.TryParse(_productVersionContents, version: out productVersion); writer.Write((DWORD)0xFEEF04BD); writer.Write((DWORD)0x00010000); writer.Write((DWORD)((uint)fileVersion.Major << 16) | (uint)fileVersion.Minor); writer.Write((DWORD)((uint)fileVersion.Build << 16) | (uint)fileVersion.Revision); writer.Write((DWORD)((uint)productVersion.Major << 16) | (uint)productVersion.Minor); writer.Write((DWORD)((uint)productVersion.Build << 16) | (uint)productVersion.Revision); writer.Write((DWORD)0x0000003F); //VS_FFI_FILEFLAGSMASK (EDMAURER) really? all these bits are valid? writer.Write((DWORD)0); //file flags writer.Write((DWORD)0x00000004); //VOS__WINDOWS32 writer.Write((DWORD)this.FileType); writer.Write((DWORD)0); //file subtype writer.Write((DWORD)0); //date most sig writer.Write((DWORD)0); //date least sig } /// <summary> /// Assume that 3 WORDs preceded this string and that they began 32-bit aligned. /// Given the string length compute the number of bytes that should be written to end /// the buffer on a 32-bit boundary</summary> /// <param name="cb"></param> /// <returns></returns> private static int PadKeyLen(int cb) { //add previously written 3 WORDS, round up, then subtract the 3 WORDS. return PadToDword(cb + 3 * sizeof(WORD)) - 3 * sizeof(WORD); } /// <summary> /// assuming the length of bytes submitted began on a 32-bit boundary, /// round up this length as necessary so that it ends at a 32-bit boundary. /// </summary> /// <param name="cb"></param> /// <returns></returns> private static int PadToDword(int cb) { return (cb + 3) & ~3; } private const int HDRSIZE = 3 * sizeof(ushort); private static ushort SizeofVerString(string lpszKey, string lpszValue) { int cbKey, cbValue; cbKey = (lpszKey.Length + 1) * 2; // Make room for the NULL cbValue = (lpszValue.Length + 1) * 2; return checked((ushort)(PadKeyLen(cbKey) + // key, 0 padded to DWORD boundary cbValue + // value HDRSIZE)); // block header. } private static void WriteVersionString(KeyValuePair<string, string> keyValuePair, BinaryWriter writer) { RoslynDebug.Assert(keyValuePair.Value != null); ushort cbBlock = SizeofVerString(keyValuePair.Key, keyValuePair.Value); int cbKey = (keyValuePair.Key.Length + 1) * 2; // includes terminating NUL int cbVal = (keyValuePair.Value.Length + 1) * 2; // includes terminating NUL var startPos = writer.BaseStream.Position; Debug.Assert((startPos & 3) == 0); writer.Write((WORD)cbBlock); writer.Write((WORD)(keyValuePair.Value.Length + 1)); //add 1 for nul writer.Write((WORD)1); writer.Write(keyValuePair.Key.ToCharArray()); writer.Write((WORD)'\0'); writer.Write(new byte[PadKeyLen(cbKey) - cbKey]); Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write(keyValuePair.Value.ToCharArray()); writer.Write((WORD)'\0'); //writer.Write(new byte[PadToDword(cbVal) - cbVal]); System.Diagnostics.Debug.Assert(cbBlock == writer.BaseStream.Position - startPos); } /// <summary> /// compute number of chars needed to end up on a 32-bit boundary assuming that three /// WORDS preceded this string. /// </summary> /// <param name="sz"></param> /// <returns></returns> private static int KEYSIZE(string sz) { return PadKeyLen((sz.Length + 1) * sizeof(WCHAR)) / sizeof(WCHAR); } private static int KEYBYTES(string sz) { return KEYSIZE(sz) * sizeof(WCHAR); } private int GetStringsSize() { int sum = 0; foreach (var verString in GetVerStrings()) { sum = (sum + 3) & ~3; //ensure that each String data structure starts on a 32bit boundary. sum += SizeofVerString(verString.Key, verString.Value); } return sum; } internal int GetDataSize() { int sizeEXEVERRESOURCE = sizeof(WORD) * 3 * 5 + 2 * sizeof(WORD) + //five headers + two words for CP and lang KEYBYTES(vsVersionInfoKey) + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey) + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + sizeVS_FIXEDFILEINFO; return GetStringsSize() + sizeEXEVERRESOURCE; } internal void WriteVerResource(BinaryWriter writer) { /* must be assumed to start on a 32-bit boundary. * * the sub-elements of the VS_VERSIONINFO consist of a header (3 WORDS) a string * and then beginning on the next 32-bit boundary, the elements children struct VS_VERSIONINFO { WORD cbRootBlock; // size of whole resource WORD cbRootValue; // size of VS_FIXEDFILEINFO structure WORD fRootText; // root is text? WCHAR szRootKey[KEYSIZE("VS_VERSION_INFO")]; // Holds "VS_VERSION_INFO" VS_FIXEDFILEINFO vsFixed; // fixed information. WORD cbVarBlock; // size of VarFileInfo block WORD cbVarValue; // always 0 WORD fVarText; // VarFileInfo is text? WCHAR szVarKey[KEYSIZE("VarFileInfo")]; // Holds "VarFileInfo" WORD cbTransBlock; // size of Translation block WORD cbTransValue; // size of Translation value WORD fTransText; // Translation is text? WCHAR szTransKey[KEYSIZE("Translation")]; // Holds "Translation" WORD langid; // language id WORD codepage; // codepage id WORD cbStringBlock; // size of StringFileInfo block WORD cbStringValue; // always 0 WORD fStringText; // StringFileInfo is text? WCHAR szStringKey[KEYSIZE("StringFileInfo")]; // Holds "StringFileInfo" WORD cbLangCpBlock; // size of language/codepage block WORD cbLangCpValue; // always 0 WORD fLangCpText; // LangCp is text? WCHAR szLangCpKey[KEYSIZE("12345678")]; // Holds hex version of language/codepage // followed by strings }; */ var debugPos = writer.BaseStream.Position; var dataSize = GetDataSize(); writer.Write((WORD)dataSize); writer.Write((WORD)sizeVS_FIXEDFILEINFO); writer.Write((WORD)0); writer.Write(vsVersionInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(vsVersionInfoKey) - vsVersionInfoKey.Length * 2]); System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); WriteVSFixedFileInfo(writer); writer.Write((WORD)(sizeof(WORD) * 2 + 2 * HDRSIZE + KEYBYTES(varFileInfoKey) + KEYBYTES(translationKey))); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(varFileInfoKey.ToCharArray()); writer.Write(new byte[KEYBYTES(varFileInfoKey) - varFileInfoKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(sizeof(WORD) * 2 + HDRSIZE + KEYBYTES(translationKey))); writer.Write((WORD)(sizeof(WORD) * 2)); writer.Write((WORD)0); writer.Write(translationKey.ToCharArray()); writer.Write(new byte[KEYBYTES(translationKey) - translationKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)0); //langId; MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)) = 0 writer.Write((WORD)CP_WINUNICODE); //codepage; 1200 = CP_WINUNICODE System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(2 * HDRSIZE + KEYBYTES(stringFileInfoKey) + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(stringFileInfoKey.ToCharArray()); //actually preceded by 5 WORDS so not consistent with the //assumptions of KEYBYTES, but equivalent. writer.Write(new byte[KEYBYTES(stringFileInfoKey) - stringFileInfoKey.Length * 2]); //padding. System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); writer.Write((WORD)(HDRSIZE + KEYBYTES(_langIdAndCodePageKey) + GetStringsSize())); writer.Write((WORD)0); writer.Write((WORD)1); writer.Write(_langIdAndCodePageKey.ToCharArray()); writer.Write(new byte[KEYBYTES(_langIdAndCodePageKey) - _langIdAndCodePageKey.Length * 2]); //padding System.Diagnostics.Debug.Assert((writer.BaseStream.Position & 3) == 0); System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == dataSize - GetStringsSize()); debugPos = writer.BaseStream.Position; foreach (var entry in GetVerStrings()) { var writerPos = writer.BaseStream.Position; //write any padding necessary to align the String struct on a 32 bit boundary. writer.Write(new byte[((writerPos + 3) & ~3) - writerPos]); System.Diagnostics.Debug.Assert(entry.Value != null); WriteVersionString(entry, writer); } System.Diagnostics.Debug.Assert(writer.BaseStream.Position - debugPos == GetStringsSize()); } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithDiscoverEditorConfigFiles.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ConsoleApplication62</RootNamespace> <AssemblyName>ConsoleApplication62</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProjectGuid>{9705A8E6-C854-4FD3-8CEA-EDBDD54C7FD8}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>ConsoleApplication62</RootNamespace> <AssemblyName>ConsoleApplication62</AssemblyName> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <DiscoverEditorConfigFiles>true</DiscoverEditorConfigFiles> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <PlatformTarget>AnyCPU</PlatformTarget> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> <Reference Include="System.Xml" /> <Reference Include="System.Xml.Linq" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/Analyzers/RemoveUnnecessaryImports/AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CodeActions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal abstract class AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { // NOTE: This is a trigger diagnostic, which doesn't show up in the ruleset editor and hence doesn't need a conventional IDE Diagnostic ID string. internal const string DiagnosticFixableId = "RemoveUnnecessaryImportsFixable"; // The NotConfigurable custom tag ensures that user can't turn this diagnostic into a warning / error via // ruleset editor or solution explorer. Setting messageFormat to empty string ensures that we won't display // this diagnostic in the preview pane header. #pragma warning disable RS0030 // Do not used banned APIs - We cannot use AbstractBuiltInCodeStyleDiagnosticAnalyzer nor AbstractCodeQualityDiagnosticAnalyzer. // This analyzer is run against generated code while the abstract base classes mentioned doesn't. private static readonly DiagnosticDescriptor s_fixableIdDescriptor = new(DiagnosticFixableId, title: "", messageFormat: "", category: "", defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs private readonly DiagnosticDescriptor _unnecessaryClassificationIdDescriptor; private readonly DiagnosticDescriptor _classificationIdDescriptor; private readonly DiagnosticDescriptor _unnecessaryGeneratedCodeClassificationIdDescriptor; private readonly DiagnosticDescriptor _generatedCodeClassificationIdDescriptor; protected AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer() { var titleAndMessageFormat = GetTitleAndMessageFormatForClassificationIdDescriptor(); #pragma warning disable RS0030 // Do not used banned APIs _unnecessaryClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()).ToArray()); _classificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()); _unnecessaryGeneratedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.UnnecessaryAndNotConfigurable); _generatedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs } protected abstract LocalizableString GetTitleAndMessageFormatForClassificationIdDescriptor(); protected abstract ImmutableArray<SyntaxNode> MergeImports(ImmutableArray<SyntaxNode> unnecessaryImports); protected abstract bool IsRegularCommentOrDocComment(SyntaxTrivia trivia); protected abstract IUnnecessaryImportsProvider UnnecessaryImportsProvider { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create( s_fixableIdDescriptor, _unnecessaryClassificationIdDescriptor, _classificationIdDescriptor, _unnecessaryGeneratedCodeClassificationIdDescriptor, _generatedCodeClassificationIdDescriptor); } } public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) => false; public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSemanticModelAction(AnalyzeSemanticModel); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var language = context.SemanticModel.Language; var unnecessaryImports = UnnecessaryImportsProvider.GetUnnecessaryImports(context.SemanticModel, cancellationToken); if (unnecessaryImports.Any()) { // The IUnnecessaryImportsService will return individual import pieces that // need to be removed. For example, it will return individual import-clauses // from VB. However, we want to mark the entire import statement if we are // going to remove all the clause. Defer to our subclass to stitch this up // for us appropriately. unnecessaryImports = MergeImports(unnecessaryImports); var fadeOut = ShouldFade(context.Options, tree, language, cancellationToken); DiagnosticDescriptor descriptor; if (GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocComment, cancellationToken)) { descriptor = fadeOut ? _unnecessaryGeneratedCodeClassificationIdDescriptor : _generatedCodeClassificationIdDescriptor; } else { descriptor = fadeOut ? _unnecessaryClassificationIdDescriptor : _classificationIdDescriptor; } var getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unnecessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree, descriptor, cancellationToken).Concat( CreateFixableDiagnostics(unnecessaryImports, tree, cancellationToken)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } static bool ShouldFade(AnalyzerOptions options, SyntaxTree tree, string language, CancellationToken cancellationToken) { return options.GetOption(FadingOptions.FadeOutUnusedImports, language, tree, cancellationToken); } } protected virtual Func<SyntaxNode, SyntaxToken>? GetLastTokenDelegateForContiguousSpans() => null; // Create one diagnostic for each unnecessary span that will be classified as Unnecessary private static IEnumerable<Diagnostic> CreateClassificationDiagnostics( IEnumerable<TextSpan> contiguousSpans, SyntaxTree tree, DiagnosticDescriptor descriptor, CancellationToken cancellationToken) { foreach (var span in contiguousSpans) { if (tree.OverlapsHiddenPosition(span, cancellationToken)) { continue; } yield return Diagnostic.Create(descriptor, tree.GetLocation(span)); } } protected abstract IEnumerable<TextSpan> GetFixableDiagnosticSpans( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken); private IEnumerable<Diagnostic> CreateFixableDiagnostics( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken) { var spans = GetFixableDiagnosticSpans(nodes, tree, cancellationToken); foreach (var span in spans) { yield return Diagnostic.Create(s_fixableIdDescriptor, tree.GetLocation(span)); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Fading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CodeActions; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #else using Microsoft.CodeAnalysis.Options; #endif namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal abstract class AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { // NOTE: This is a trigger diagnostic, which doesn't show up in the ruleset editor and hence doesn't need a conventional IDE Diagnostic ID string. internal const string DiagnosticFixableId = "RemoveUnnecessaryImportsFixable"; // The NotConfigurable custom tag ensures that user can't turn this diagnostic into a warning / error via // ruleset editor or solution explorer. Setting messageFormat to empty string ensures that we won't display // this diagnostic in the preview pane header. #pragma warning disable RS0030 // Do not used banned APIs - We cannot use AbstractBuiltInCodeStyleDiagnosticAnalyzer nor AbstractCodeQualityDiagnosticAnalyzer. // This analyzer is run against generated code while the abstract base classes mentioned doesn't. private static readonly DiagnosticDescriptor s_fixableIdDescriptor = new(DiagnosticFixableId, title: "", messageFormat: "", category: "", defaultSeverity: DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs private readonly DiagnosticDescriptor _unnecessaryClassificationIdDescriptor; private readonly DiagnosticDescriptor _classificationIdDescriptor; private readonly DiagnosticDescriptor _unnecessaryGeneratedCodeClassificationIdDescriptor; private readonly DiagnosticDescriptor _generatedCodeClassificationIdDescriptor; protected AbstractRemoveUnnecessaryImportsDiagnosticAnalyzer() { var titleAndMessageFormat = GetTitleAndMessageFormatForClassificationIdDescriptor(); #pragma warning disable RS0030 // Do not used banned APIs _unnecessaryClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.Unnecessary.Concat(EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()).ToArray()); _classificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId, titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: EnforceOnBuildValues.RemoveUnnecessaryImports.ToCustomTag()); _unnecessaryGeneratedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.UnnecessaryAndNotConfigurable); _generatedCodeClassificationIdDescriptor = new DiagnosticDescriptor(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId + "_gen", titleAndMessageFormat, titleAndMessageFormat, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, helpLinkUri: DiagnosticHelper.GetHelpLinkForDiagnosticId(IDEDiagnosticIds.RemoveUnnecessaryImportsDiagnosticId), customTags: DiagnosticCustomTags.NotConfigurable); #pragma warning restore RS0030 // Do not used banned APIs } protected abstract LocalizableString GetTitleAndMessageFormatForClassificationIdDescriptor(); protected abstract ImmutableArray<SyntaxNode> MergeImports(ImmutableArray<SyntaxNode> unnecessaryImports); protected abstract bool IsRegularCommentOrDocComment(SyntaxTrivia trivia); protected abstract IUnnecessaryImportsProvider UnnecessaryImportsProvider { get; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create( s_fixableIdDescriptor, _unnecessaryClassificationIdDescriptor, _classificationIdDescriptor, _unnecessaryGeneratedCodeClassificationIdDescriptor, _generatedCodeClassificationIdDescriptor); } } public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(OptionSet options) => false; public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterSemanticModelAction(AnalyzeSemanticModel); } private void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var tree = context.SemanticModel.SyntaxTree; var cancellationToken = context.CancellationToken; var language = context.SemanticModel.Language; var unnecessaryImports = UnnecessaryImportsProvider.GetUnnecessaryImports(context.SemanticModel, cancellationToken); if (unnecessaryImports.Any()) { // The IUnnecessaryImportsService will return individual import pieces that // need to be removed. For example, it will return individual import-clauses // from VB. However, we want to mark the entire import statement if we are // going to remove all the clause. Defer to our subclass to stitch this up // for us appropriately. unnecessaryImports = MergeImports(unnecessaryImports); var fadeOut = ShouldFade(context.Options, tree, language, cancellationToken); DiagnosticDescriptor descriptor; if (GeneratedCodeUtilities.IsGeneratedCode(tree, IsRegularCommentOrDocComment, cancellationToken)) { descriptor = fadeOut ? _unnecessaryGeneratedCodeClassificationIdDescriptor : _generatedCodeClassificationIdDescriptor; } else { descriptor = fadeOut ? _unnecessaryClassificationIdDescriptor : _classificationIdDescriptor; } var getLastTokenFunc = GetLastTokenDelegateForContiguousSpans(); var contiguousSpans = unnecessaryImports.GetContiguousSpans(getLastTokenFunc); var diagnostics = CreateClassificationDiagnostics(contiguousSpans, tree, descriptor, cancellationToken).Concat( CreateFixableDiagnostics(unnecessaryImports, tree, cancellationToken)); foreach (var diagnostic in diagnostics) { context.ReportDiagnostic(diagnostic); } } static bool ShouldFade(AnalyzerOptions options, SyntaxTree tree, string language, CancellationToken cancellationToken) { return options.GetOption(FadingOptions.FadeOutUnusedImports, language, tree, cancellationToken); } } protected virtual Func<SyntaxNode, SyntaxToken>? GetLastTokenDelegateForContiguousSpans() => null; // Create one diagnostic for each unnecessary span that will be classified as Unnecessary private static IEnumerable<Diagnostic> CreateClassificationDiagnostics( IEnumerable<TextSpan> contiguousSpans, SyntaxTree tree, DiagnosticDescriptor descriptor, CancellationToken cancellationToken) { foreach (var span in contiguousSpans) { if (tree.OverlapsHiddenPosition(span, cancellationToken)) { continue; } yield return Diagnostic.Create(descriptor, tree.GetLocation(span)); } } protected abstract IEnumerable<TextSpan> GetFixableDiagnosticSpans( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken); private IEnumerable<Diagnostic> CreateFixableDiagnostics( IEnumerable<SyntaxNode> nodes, SyntaxTree tree, CancellationToken cancellationToken) { var spans = GetFixableDiagnosticSpans(nodes, tree, cancellationToken); foreach (var span in spans) { yield return Diagnostic.Create(s_fixableIdDescriptor, tree.GetLocation(span)); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/SymbolSearchUpdateEngine.DatabaseFactoryService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Microsoft.CodeAnalysis.Elfie.Model; namespace Microsoft.CodeAnalysis.SymbolSearch { internal partial class SymbolSearchUpdateEngine { private class DatabaseFactoryService : IDatabaseFactoryService { public AddReferenceDatabase CreateDatabaseFromBytes(byte[] bytes) { using var memoryStream = new MemoryStream(bytes); using var streamReader = new StreamReader(memoryStream); var database = new AddReferenceDatabase(ArdbVersion.V1); database.ReadText(streamReader); return database; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Microsoft.CodeAnalysis.Elfie.Model; namespace Microsoft.CodeAnalysis.SymbolSearch { internal partial class SymbolSearchUpdateEngine { private class DatabaseFactoryService : IDatabaseFactoryService { public AddReferenceDatabase CreateDatabaseFromBytes(byte[] bytes) { using var memoryStream = new MemoryStream(bytes); using var streamReader = new StreamReader(memoryStream); var database = new AddReferenceDatabase(ArdbVersion.V1); database.ReadText(streamReader); return database; } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/ExpressionEvaluator/VisualBasic/Source/ResultProvider/VisualBasicFormatter.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.ObjectModel Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Microsoft.VisualStudio.Debugger.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' <summary> ''' Computes string representations of <see cref="DkmClrValue"/> instances. ''' </summary> Partial Friend NotInheritable Class VisualBasicFormatter Inherits Formatter ''' <summary> ''' Singleton instance of VisualBasicFormatter (created using default constructor). ''' </summary> Friend Shared ReadOnly Instance As VisualBasicFormatter = New VisualBasicFormatter() Public Sub New() MyBase.New(defaultFormat:="{{{0}}}", nullString:="Nothing", thisString:="Me") End Sub Friend Overrides Function IsValidIdentifier(name As String) As Boolean Return SyntaxFacts.IsValidIdentifier(name) End Function Friend Overrides Function IsIdentifierPartCharacter(c As Char) As Boolean Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Friend Overrides Function IsPredefinedType(type As Type) As Boolean Return type.IsPredefinedType() End Function Friend Overrides Function IsWhitespace(c As Char) As Boolean Return SyntaxFacts.IsWhitespace(c) End Function ' TODO https://github.com/dotnet/roslyn/issues/37536 ' This parsing is imprecise and may result in bad expressions. Friend Overrides Function TrimAndGetFormatSpecifiers(expression As String, ByRef formatSpecifiers As ReadOnlyCollection(Of String)) As String expression = RemoveComments(expression) expression = RemoveFormatSpecifiers(expression, formatSpecifiers) Return RemoveLeadingAndTrailingWhitespace(expression) End Function Private Shared Function RemoveComments(expression As String) As String ' Workaround for https://dev.azure.com/devdiv/DevDiv/_workitems/edit/847849 ' Do not remove any comments that might be in a string. ' This won't work when there are quotes in the comment, but that's not that common. Dim lastQuote As Integer = expression.LastIndexOf(""""c) + 1 Dim index = expression.IndexOf("'"c, lastQuote) If index < 0 Then Return expression End If Return expression.Substring(0, index) 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.ObjectModel Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.VisualStudio.Debugger.ComponentInterfaces Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation Imports Microsoft.VisualStudio.Debugger.Metadata Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator ''' <summary> ''' Computes string representations of <see cref="DkmClrValue"/> instances. ''' </summary> Partial Friend NotInheritable Class VisualBasicFormatter Inherits Formatter ''' <summary> ''' Singleton instance of VisualBasicFormatter (created using default constructor). ''' </summary> Friend Shared ReadOnly Instance As VisualBasicFormatter = New VisualBasicFormatter() Public Sub New() MyBase.New(defaultFormat:="{{{0}}}", nullString:="Nothing", thisString:="Me") End Sub Friend Overrides Function IsValidIdentifier(name As String) As Boolean Return SyntaxFacts.IsValidIdentifier(name) End Function Friend Overrides Function IsIdentifierPartCharacter(c As Char) As Boolean Return SyntaxFacts.IsIdentifierPartCharacter(c) End Function Friend Overrides Function IsPredefinedType(type As Type) As Boolean Return type.IsPredefinedType() End Function Friend Overrides Function IsWhitespace(c As Char) As Boolean Return SyntaxFacts.IsWhitespace(c) End Function ' TODO https://github.com/dotnet/roslyn/issues/37536 ' This parsing is imprecise and may result in bad expressions. Friend Overrides Function TrimAndGetFormatSpecifiers(expression As String, ByRef formatSpecifiers As ReadOnlyCollection(Of String)) As String expression = RemoveComments(expression) expression = RemoveFormatSpecifiers(expression, formatSpecifiers) Return RemoveLeadingAndTrailingWhitespace(expression) End Function Private Shared Function RemoveComments(expression As String) As String ' Workaround for https://dev.azure.com/devdiv/DevDiv/_workitems/edit/847849 ' Do not remove any comments that might be in a string. ' This won't work when there are quotes in the comment, but that's not that common. Dim lastQuote As Integer = expression.LastIndexOf(""""c) + 1 Dim index = expression.IndexOf("'"c, lastQuote) If index < 0 Then Return expression End If Return expression.Substring(0, index) End Function End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Lowering/LocalRewriter/LoweredDynamicOperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LoweredDynamicOperationFactory { private readonly SyntheticBoundNodeFactory _factory; private readonly int _methodOrdinal; private readonly int _localFunctionOrdinal; private NamedTypeSymbol? _currentDynamicCallSiteContainer; private int _callSiteIdDispenser; internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1) { Debug.Assert(factory != null); _factory = factory; _methodOrdinal = methodOrdinal; _localFunctionOrdinal = localFunctionOrdinal; } public int MethodOrdinal => _methodOrdinal; // We could read the values of the following enums from metadata instead of hardcoding them here but // - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning, // - if any new flags are added to the runtime binder the compiler will change as well to produce them. // The only scenario that is not supported by hardcoding the values is when a completely new Framework is created // that redefines these constants and is not supposed to run existing programs. /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags. /// </summary> [Flags] private enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256, } /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags. /// </summary> [Flags] private enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32, } internal LoweredDynamicOperation MakeDynamicConversion( BoundExpression loweredOperand, bool isExplicit, bool isArrayIndex, bool isChecked, TypeSymbol resultType) { _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; Debug.Assert(!isExplicit || !isArrayIndex); if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (isExplicit) { binderFlags |= CSharpBinderFlags.ConvertExplicit; } if (isArrayIndex) { binderFlags |= CSharpBinderFlags.ConvertArrayIndex; } var loweredArguments = ImmutableArray.Create(loweredOperand); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[] { // flags: _factory.Literal((int)binderFlags), // target type: _factory.Typeof(resultType), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicUnaryOperator( UnaryOperatorKind operatorKind, BoundExpression loweredOperand, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } var loweredArguments = ImmutableArray.Create(loweredOperand); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType()), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicBinaryOperator( BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, bool isCompoundAssignment, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredLeft.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (operatorKind.IsLogical()) { binderFlags |= CSharpBinderFlags.BinaryOperationLogical; } var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicMemberInvocation( string name, BoundExpression loweredReceiver, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool hasImplicitReceiver, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; Debug.Assert(_factory.TopLevelMethod is { }); CSharpBinderFlags binderFlags = 0; if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver) { binderFlags |= CSharpBinderFlags.InvokeSimpleName; } TypeSymbol resultType; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } RefKind receiverRefKind; bool receiverIsStaticType; if (loweredReceiver.Kind == BoundKind.TypeExpression) { loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type); receiverRefKind = RefKind.None; receiverIsStaticType = true; } else { receiverRefKind = GetReceiverRefKind(loweredReceiver); receiverIsStaticType = false; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(name), // type arguments: typeArgumentsWithAnnotations.IsDefaultOrEmpty ? _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) : _factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation( string accessorName, BoundExpression loweredReceiver, BoundExpression loweredHandler) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded; var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = AssemblySymbol.DynamicType; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(accessorName), // type arguments: _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType); } internal LoweredDynamicOperation MakeDynamicInvocation( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; TypeSymbol resultType; CSharpBinderFlags binderFlags = 0; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[] { // flags: _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicConstructorInvocation( SyntaxNode syntax, TypeSymbol type, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = syntax; var loweredReceiver = _factory.Typeof(type); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[] { // flags: _factory.Literal(0), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type); } internal LoweredDynamicOperation MakeDynamicGetMember( BoundExpression loweredReceiver, string name, bool resultIndexed) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (resultIndexed) { binderFlags |= CSharpBinderFlags.ResultIndexed; } var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicSetMember( BoundExpression loweredReceiver, string name, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredArguments = ImmutableArray<BoundExpression>.Empty; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType); } internal LoweredDynamicOperation MakeDynamicGetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = loweredReceiver.Syntax; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[] { // flags (unused): _factory.Literal((int)CSharpBinderFlags.None), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicSetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver); var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[] { // flags (unused): _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType); } internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver) { _factory.Syntax = loweredReceiver.Syntax; var resultType = _factory.SpecialType(SpecialType.System_Boolean); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[] { // flags (unused): _factory.Literal((int)0), // member name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType); } private MethodSymbol GetArgumentInfoFactory() { return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create); } private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args) { var binderFactory = _factory.WellKnownMember(factoryMethod); if (binderFactory is null) { return null; } return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull()); } // If we have a struct calling object, then we need to pass it by ref, provided // that it was an Lvalue. For instance, // Struct s = ...; dynamic d = ...; // s.M(d); // becomes Site(ref s, d) // however // dynamic d = ...; // GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver) { Debug.Assert(loweredReceiver.Type is { }); if (!loweredReceiver.Type.IsValueType) { return RefKind.None; } switch (loweredReceiver.Kind) { case BoundKind.Local: case BoundKind.Parameter: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: return RefKind.Ref; case BoundKind.BaseReference: // base dynamic dispatch is not supported, an error has already been reported case BoundKind.TypeExpression: throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind); } return RefKind.None; } internal BoundExpression MakeCallSiteArgumentInfos( MethodSymbol argumentInfoFactory, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames = default(ImmutableArray<string>), ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), BoundExpression? loweredReceiver = null, RefKind receiverRefKind = RefKind.None, bool receiverIsStaticType = false, BoundExpression? loweredRight = null) { const string? NoName = null; Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length); Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length); Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None); var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)]; int j = 0; if (loweredReceiver != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType); } for (int i = 0; i < loweredArguments.Length; i++) { infos[j++] = GetArgumentInfo( argumentInfoFactory, loweredArguments[i], argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i], refKinds.IsDefault ? RefKind.None : refKinds[i], isStaticType: false); } if (loweredRight != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false); } return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos); } internal LoweredDynamicOperation MakeDynamicOperation( BoundExpression? binderConstruction, BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(!loweredArguments.IsDefault); // get well-known types and members we need: NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType); NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create); FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target); MethodSymbol delegateInvoke; if (binderConstruction == null || delegateTypeOverMethodTypeParameters is null || delegateTypeOverMethodTypeParameters.IsErrorType() || (delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null || callSiteTypeGeneric.IsErrorType() || callSiteFactoryGeneric is null || callSiteTargetFieldGeneric is null) { // CS1969: One or more types required to compile a dynamic expression cannot be found. // Dev11 reports it with source location for each dynamic operation, which results in many error messages. // The diagnostic that names the specific missing type or member has already been reported. _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton); return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType); } if (_currentDynamicCallSiteContainer is null) { _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal); } var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition; var methodToContainerTypeParametersMap = containerDef.TypeMap; ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments); var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters }); var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType); var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType); var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap); var callSiteFieldAccess = _factory.Field(null, callSiteField); var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight); var nullCallSite = _factory.Null(callSiteField.Type); var siteInitialization = _factory.Conditional( _factory.ObjectEqual(callSiteFieldAccess, nullCallSite), _factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)), nullCallSite, callSiteField.Type); var siteInvocation = _factory.Call( _factory.Field(callSiteFieldAccess, callSiteTargetField), delegateInvoke, callSiteArguments); return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps); } /// <summary> /// If there are any discards in the arguments, create locals for each, updates the arguments and /// returns the symbols that were created. /// Returns default if no discards found. /// </summary> private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments) { int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression); if (discardCount == 0) { return ImmutableArray<LocalSymbol>.Empty; } ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount); loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder); return temporariesBuilder.ToImmutableAndFree(); } private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal) { Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { }); Debug.Assert(factory.TopLevelMethod is { }); Debug.Assert(factory.CurrentFunction is { }); // We don't reuse call-sites during EnC. Each edit creates a new container and sites. int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation); var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction); factory.AddNestedType(synthesizedContainer); if (!synthesizedContainer.TypeParameters.IsEmpty) { return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); } return synthesizedContainer; } internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap) { var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++); var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters); var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); _factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax); callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters }); var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true); _factory.AddField(containerDefinition, field); Debug.Assert(_currentDynamicCallSiteContainer is { }); return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field; } internal NamedTypeSymbol? GetDelegateType( BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length); var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite); if (callSiteType.IsErrorType()) { return null; } var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType); bool returnsVoid = resultType.IsVoidType(); bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty; if (!hasByRefs) { var wkDelegateType = returnsVoid ? WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType); if (!delegateType.HasUseSiteError) { _factory.Diagnostics.AddDependencies(delegateType); return delegateType.Construct(delegateSignature); } } } RefKindVector byRefs; if (hasByRefs) { byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1)); int j = 1; if (loweredReceiver != null) { byRefs[j++] = getRefKind(receiverRefKind); } if (!refKinds.IsDefault) { for (int i = 0; i < refKinds.Length; i++, j++) { byRefs[j] = getRefKind(refKinds[i]); } } if (!returnsVoid) { byRefs[j++] = RefKind.None; } } else { byRefs = default(RefKindVector); } int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1); Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { }); int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation); return synthesizedType.Construct(delegateSignature); // The distinction between by-ref kinds is ignored for dynamic call-sites. static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref; } private BoundExpression GetArgumentInfo( MethodSymbol argumentInfoFactory, BoundExpression boundArgument, string? name, RefKind refKind, bool isStaticType) { CSharpArgumentInfoFlags flags = 0; if (isStaticType) { flags |= CSharpArgumentInfoFlags.IsStaticType; } if (name != null) { flags |= CSharpArgumentInfoFlags.NamedArgument; } Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic"); // by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType if (refKind == RefKind.Out) { flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType; } else if (refKind == RefKind.Ref) { flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType; } var argType = boundArgument.Type; // Check "literal" constant. // What the runtime binder does with this LiteralConstant flag is just to create a constant, // which is a compelling enough reason to make sure that on the production end of the binder // data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant // argument. // And in fact, the bug being fixed with this change is that the compiler will consider constants // for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but // the runtime binder didn't. So we do need to set this flag whenever we see a constant. // But the complication is that null values lose their type when they get to the runtime binder, // and so we need a way to distinguish a null constant of any given type from the null literal. // The design is simple! We use UseCompileTimeType to determine whether we care about the type of // a null constant argument, so that the null literal gets "LiteralConstant" whereas every other // constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is // wrong for the null literal. // We care, because we want to prevent this from working: // // const C x = null; // class C { public void M(SomeUnrelatedReferenceType x) { } } // ... // dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone! // // as well as the alternative where x is a const null of type object. if (boundArgument.ConstantValue != null) { flags |= CSharpArgumentInfoFlags.Constant; } // Check compile time type. // See also DynamicRewriter::GenerateCallingObjectFlags. if (argType is { } && !argType.IsDynamic()) { flags |= CSharpArgumentInfoFlags.UseCompileTimeType; } return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name)); } private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right) { var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)]; int j = 0; result[j++] = callSiteFieldAccess; if (receiver != null) { result[j++] = receiver; } arguments.CopyTo(result, j); j += arguments.Length; if (right != null) { result[j++] = right; } return result.AsImmutableOrNull(); } private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType) { var systemObjectType = _factory.SpecialType(SpecialType.System_Object); var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)]; int j = 0; // CallSite: result[j++] = callSiteType; // receiver: if (receiver != null) { result[j++] = receiver.Type ?? systemObjectType; } // argument types: for (int i = 0; i < arguments.Length; i++) { result[j++] = arguments[i].Type ?? systemObjectType; } // right hand side of an assignment: if (right != null) { result[j++] = right.Type ?? systemObjectType; } // return type: if (j < result.Length) { result[j++] = resultType ?? systemObjectType; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LoweredDynamicOperationFactory { private readonly SyntheticBoundNodeFactory _factory; private readonly int _methodOrdinal; private readonly int _localFunctionOrdinal; private NamedTypeSymbol? _currentDynamicCallSiteContainer; private int _callSiteIdDispenser; internal LoweredDynamicOperationFactory(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal = -1) { Debug.Assert(factory != null); _factory = factory; _methodOrdinal = methodOrdinal; _localFunctionOrdinal = localFunctionOrdinal; } public int MethodOrdinal => _methodOrdinal; // We could read the values of the following enums from metadata instead of hardcoding them here but // - they can never change since existing programs have the values inlined and would be broken if the values changed their meaning, // - if any new flags are added to the runtime binder the compiler will change as well to produce them. // The only scenario that is not supported by hardcoding the values is when a completely new Framework is created // that redefines these constants and is not supposed to run existing programs. /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags. /// </summary> [Flags] private enum CSharpBinderFlags { None = 0, CheckedContext = 1, InvokeSimpleName = 2, InvokeSpecialName = 4, BinaryOperationLogical = 8, ConvertExplicit = 16, ConvertArrayIndex = 32, ResultIndexed = 64, ValueFromCompoundAssignment = 128, ResultDiscarded = 256, } /// <summary> /// Corresponds to Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags. /// </summary> [Flags] private enum CSharpArgumentInfoFlags { None = 0, UseCompileTimeType = 1, Constant = 2, NamedArgument = 4, IsRef = 8, IsOut = 16, IsStaticType = 32, } internal LoweredDynamicOperation MakeDynamicConversion( BoundExpression loweredOperand, bool isExplicit, bool isArrayIndex, bool isChecked, TypeSymbol resultType) { _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; Debug.Assert(!isExplicit || !isArrayIndex); if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (isExplicit) { binderFlags |= CSharpBinderFlags.ConvertExplicit; } if (isArrayIndex) { binderFlags |= CSharpBinderFlags.ConvertArrayIndex; } var loweredArguments = ImmutableArray.Create(loweredOperand); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Convert, new[] { // flags: _factory.Literal((int)binderFlags), // target type: _factory.Typeof(resultType), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicUnaryOperator( UnaryOperatorKind operatorKind, BoundExpression loweredOperand, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredOperand.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } var loweredArguments = ImmutableArray.Create(loweredOperand); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__UnaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType()), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicBinaryOperator( BinaryOperatorKind operatorKind, BoundExpression loweredLeft, BoundExpression loweredRight, bool isCompoundAssignment, TypeSymbol resultType) { Debug.Assert(operatorKind.IsDynamic()); _factory.Syntax = loweredLeft.Syntax; CSharpBinderFlags binderFlags = 0; if (operatorKind.IsChecked()) { binderFlags |= CSharpBinderFlags.CheckedContext; } if (operatorKind.IsLogical()) { binderFlags |= CSharpBinderFlags.BinaryOperationLogical; } var loweredArguments = ImmutableArray.Create<BoundExpression>(loweredLeft, loweredRight); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__BinaryOperation, new[] { // flags: _factory.Literal((int)binderFlags), // expression type: _factory.Literal((int)operatorKind.ToExpressionType(isCompoundAssignment)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments) }) : null; return MakeDynamicOperation(binderConstruction, null, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicMemberInvocation( string name, BoundExpression loweredReceiver, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool hasImplicitReceiver, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; Debug.Assert(_factory.TopLevelMethod is { }); CSharpBinderFlags binderFlags = 0; if (hasImplicitReceiver && _factory.TopLevelMethod.RequiresInstanceReceiver) { binderFlags |= CSharpBinderFlags.InvokeSimpleName; } TypeSymbol resultType; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } RefKind receiverRefKind; bool receiverIsStaticType; if (loweredReceiver.Kind == BoundKind.TypeExpression) { loweredReceiver = _factory.Typeof(((BoundTypeExpression)loweredReceiver).Type); receiverRefKind = RefKind.None; receiverIsStaticType = true; } else { receiverRefKind = GetReceiverRefKind(loweredReceiver); receiverIsStaticType = false; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(name), // type arguments: typeArgumentsWithAnnotations.IsDefaultOrEmpty ? _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)) : _factory.ArrayOrEmpty(_factory.WellKnownType(WellKnownType.System_Type), _factory.TypeOfs(typeArgumentsWithAnnotations)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverRefKind, receiverIsStaticType) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, receiverRefKind, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicEventAccessorInvocation( string accessorName, BoundExpression loweredReceiver, BoundExpression loweredHandler) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = CSharpBinderFlags.InvokeSpecialName | CSharpBinderFlags.ResultDiscarded; var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = AssemblySymbol.DynamicType; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeMember, new[] { // flags: _factory.Literal((int)binderFlags), // member name: _factory.Literal(accessorName), // type arguments: _factory.Null(_factory.WellKnownArrayType(WellKnownType.System_Type)), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredHandler) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredHandler, resultType); } internal LoweredDynamicOperation MakeDynamicInvocation( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, bool resultDiscarded) { _factory.Syntax = loweredReceiver.Syntax; TypeSymbol resultType; CSharpBinderFlags binderFlags = 0; if (resultDiscarded) { binderFlags |= CSharpBinderFlags.ResultDiscarded; resultType = _factory.SpecialType(SpecialType.System_Void); } else { resultType = AssemblySymbol.DynamicType; } MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__Invoke, new[] { // flags: _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicConstructorInvocation( SyntaxNode syntax, TypeSymbol type, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = syntax; var loweredReceiver = _factory.Typeof(type); MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__InvokeConstructor, new[] { // flags: _factory.Literal(0), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, receiverIsStaticType: true) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, type); } internal LoweredDynamicOperation MakeDynamicGetMember( BoundExpression loweredReceiver, string name, bool resultIndexed) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (resultIndexed) { binderFlags |= CSharpBinderFlags.ResultIndexed; } var loweredArguments = ImmutableArray<BoundExpression>.Empty; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), null, resultType); } internal LoweredDynamicOperation MakeDynamicSetMember( BoundExpression loweredReceiver, string name, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { _factory.Syntax = loweredReceiver.Syntax; CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredArguments = ImmutableArray<BoundExpression>.Empty; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetMember, new[] { // flags: _factory.Literal((int)binderFlags), // name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, loweredReceiver: loweredReceiver, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, default(ImmutableArray<RefKind>), loweredRight, AssemblySymbol.DynamicType); } internal LoweredDynamicOperation MakeDynamicGetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds) { _factory.Syntax = loweredReceiver.Syntax; var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__GetIndex, new[] { // flags (unused): _factory.Literal((int)CSharpBinderFlags.None), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver: loweredReceiver) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, loweredArguments, refKinds, null, resultType); } internal LoweredDynamicOperation MakeDynamicSetIndex( BoundExpression loweredReceiver, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames, ImmutableArray<RefKind> refKinds, BoundExpression loweredRight, bool isCompoundAssignment = false, bool isChecked = false) { CSharpBinderFlags binderFlags = 0; if (isCompoundAssignment) { binderFlags |= CSharpBinderFlags.ValueFromCompoundAssignment; if (isChecked) { binderFlags |= CSharpBinderFlags.CheckedContext; } } var loweredReceiverRefKind = GetReceiverRefKind(loweredReceiver); var resultType = DynamicTypeSymbol.Instance; MethodSymbol argumentInfoFactory = GetArgumentInfoFactory(); var binderConstruction = ((object)argumentInfoFactory != null) ? MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__SetIndex, new[] { // flags (unused): _factory.Literal((int)binderFlags), // context: _factory.TypeofDynamicOperationContextType(), // argument infos: MakeCallSiteArgumentInfos(argumentInfoFactory, loweredArguments, argumentNames, refKinds, loweredReceiver, loweredReceiverRefKind, loweredRight: loweredRight) }) : null; return MakeDynamicOperation(binderConstruction, loweredReceiver, loweredReceiverRefKind, loweredArguments, refKinds, loweredRight, resultType); } internal LoweredDynamicOperation MakeDynamicIsEventTest(string name, BoundExpression loweredReceiver) { _factory.Syntax = loweredReceiver.Syntax; var resultType = _factory.SpecialType(SpecialType.System_Boolean); var binderConstruction = MakeBinderConstruction(WellKnownMember.Microsoft_CSharp_RuntimeBinder_Binder__IsEvent, new[] { // flags (unused): _factory.Literal((int)0), // member name: _factory.Literal(name), // context: _factory.TypeofDynamicOperationContextType() }); return MakeDynamicOperation(binderConstruction, loweredReceiver, RefKind.None, ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<RefKind>), null, resultType); } private MethodSymbol GetArgumentInfoFactory() { return _factory.WellKnownMethod(WellKnownMember.Microsoft_CSharp_RuntimeBinder_CSharpArgumentInfo__Create); } private BoundExpression? MakeBinderConstruction(WellKnownMember factoryMethod, BoundExpression[] args) { var binderFactory = _factory.WellKnownMember(factoryMethod); if (binderFactory is null) { return null; } return _factory.Call(null, (MethodSymbol)binderFactory, args.AsImmutableOrNull()); } // If we have a struct calling object, then we need to pass it by ref, provided // that it was an Lvalue. For instance, // Struct s = ...; dynamic d = ...; // s.M(d); // becomes Site(ref s, d) // however // dynamic d = ...; // GetS().M(d); // becomes Site(GetS(), d) without ref on the target obj arg internal static RefKind GetReceiverRefKind(BoundExpression loweredReceiver) { Debug.Assert(loweredReceiver.Type is { }); if (!loweredReceiver.Type.IsValueType) { return RefKind.None; } switch (loweredReceiver.Kind) { case BoundKind.Local: case BoundKind.Parameter: case BoundKind.ArrayAccess: case BoundKind.ThisReference: case BoundKind.PointerIndirectionOperator: case BoundKind.PointerElementAccess: case BoundKind.RefValueOperator: return RefKind.Ref; case BoundKind.BaseReference: // base dynamic dispatch is not supported, an error has already been reported case BoundKind.TypeExpression: throw ExceptionUtilities.UnexpectedValue(loweredReceiver.Kind); } return RefKind.None; } internal BoundExpression MakeCallSiteArgumentInfos( MethodSymbol argumentInfoFactory, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<string> argumentNames = default(ImmutableArray<string>), ImmutableArray<RefKind> refKinds = default(ImmutableArray<RefKind>), BoundExpression? loweredReceiver = null, RefKind receiverRefKind = RefKind.None, bool receiverIsStaticType = false, BoundExpression? loweredRight = null) { const string? NoName = null; Debug.Assert(argumentNames.IsDefaultOrEmpty || loweredArguments.Length == argumentNames.Length); Debug.Assert(refKinds.IsDefault || loweredArguments.Length == refKinds.Length); Debug.Assert(!receiverIsStaticType || receiverRefKind == RefKind.None); var infos = new BoundExpression[(loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0)]; int j = 0; if (loweredReceiver != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredReceiver, NoName, receiverRefKind, receiverIsStaticType); } for (int i = 0; i < loweredArguments.Length; i++) { infos[j++] = GetArgumentInfo( argumentInfoFactory, loweredArguments[i], argumentNames.IsDefaultOrEmpty ? NoName : argumentNames[i], refKinds.IsDefault ? RefKind.None : refKinds[i], isStaticType: false); } if (loweredRight != null) { infos[j++] = GetArgumentInfo(argumentInfoFactory, loweredRight, NoName, RefKind.None, isStaticType: false); } return _factory.ArrayOrEmpty(argumentInfoFactory.ContainingType, infos); } internal LoweredDynamicOperation MakeDynamicOperation( BoundExpression? binderConstruction, BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(!loweredArguments.IsDefault); // get well-known types and members we need: NamedTypeSymbol? delegateTypeOverMethodTypeParameters = GetDelegateType(loweredReceiver, receiverRefKind, loweredArguments, refKinds, loweredRight, resultType); NamedTypeSymbol callSiteTypeGeneric = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); MethodSymbol callSiteFactoryGeneric = _factory.WellKnownMethod(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Create); FieldSymbol callSiteTargetFieldGeneric = (FieldSymbol)_factory.WellKnownMember(WellKnownMember.System_Runtime_CompilerServices_CallSite_T__Target); MethodSymbol delegateInvoke; if (binderConstruction == null || delegateTypeOverMethodTypeParameters is null || delegateTypeOverMethodTypeParameters.IsErrorType() || (delegateInvoke = delegateTypeOverMethodTypeParameters.DelegateInvokeMethod) is null || callSiteTypeGeneric.IsErrorType() || callSiteFactoryGeneric is null || callSiteTargetFieldGeneric is null) { // CS1969: One or more types required to compile a dynamic expression cannot be found. // Dev11 reports it with source location for each dynamic operation, which results in many error messages. // The diagnostic that names the specific missing type or member has already been reported. _factory.Diagnostics.Add(ErrorCode.ERR_DynamicRequiredTypesMissing, NoLocation.Singleton); return LoweredDynamicOperation.Bad(loweredReceiver, loweredArguments, loweredRight, resultType); } if (_currentDynamicCallSiteContainer is null) { _currentDynamicCallSiteContainer = CreateCallSiteContainer(_factory, _methodOrdinal, _localFunctionOrdinal); } var containerDef = (SynthesizedContainer)_currentDynamicCallSiteContainer.OriginalDefinition; var methodToContainerTypeParametersMap = containerDef.TypeMap; ImmutableArray<LocalSymbol> temps = MakeTempsForDiscardArguments(ref loweredArguments); var callSiteType = callSiteTypeGeneric.Construct(new[] { delegateTypeOverMethodTypeParameters }); var callSiteFactoryMethod = callSiteFactoryGeneric.AsMember(callSiteType); var callSiteTargetField = callSiteTargetFieldGeneric.AsMember(callSiteType); var callSiteField = DefineCallSiteStorageSymbol(containerDef, delegateTypeOverMethodTypeParameters, methodToContainerTypeParametersMap); var callSiteFieldAccess = _factory.Field(null, callSiteField); var callSiteArguments = GetCallSiteArguments(callSiteFieldAccess, loweredReceiver, loweredArguments, loweredRight); var nullCallSite = _factory.Null(callSiteField.Type); var siteInitialization = _factory.Conditional( _factory.ObjectEqual(callSiteFieldAccess, nullCallSite), _factory.AssignmentExpression(callSiteFieldAccess, _factory.Call(null, callSiteFactoryMethod, binderConstruction)), nullCallSite, callSiteField.Type); var siteInvocation = _factory.Call( _factory.Field(callSiteFieldAccess, callSiteTargetField), delegateInvoke, callSiteArguments); return new LoweredDynamicOperation(_factory, siteInitialization, siteInvocation, resultType, temps); } /// <summary> /// If there are any discards in the arguments, create locals for each, updates the arguments and /// returns the symbols that were created. /// Returns default if no discards found. /// </summary> private ImmutableArray<LocalSymbol> MakeTempsForDiscardArguments(ref ImmutableArray<BoundExpression> loweredArguments) { int discardCount = loweredArguments.Count(a => a.Kind == BoundKind.DiscardExpression); if (discardCount == 0) { return ImmutableArray<LocalSymbol>.Empty; } ArrayBuilder<LocalSymbol> temporariesBuilder = ArrayBuilder<LocalSymbol>.GetInstance(discardCount); loweredArguments = _factory.MakeTempsForDiscardArguments(loweredArguments, temporariesBuilder); return temporariesBuilder.ToImmutableAndFree(); } private static NamedTypeSymbol CreateCallSiteContainer(SyntheticBoundNodeFactory factory, int methodOrdinal, int localFunctionOrdinal) { Debug.Assert(factory.CompilationState.ModuleBuilderOpt is { }); Debug.Assert(factory.TopLevelMethod is { }); Debug.Assert(factory.CurrentFunction is { }); // We don't reuse call-sites during EnC. Each edit creates a new container and sites. int generation = factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var containerName = GeneratedNames.MakeDynamicCallSiteContainerName(methodOrdinal, localFunctionOrdinal, generation); var synthesizedContainer = new DynamicSiteContainer(containerName, factory.TopLevelMethod, factory.CurrentFunction); factory.AddNestedType(synthesizedContainer); if (!synthesizedContainer.TypeParameters.IsEmpty) { return synthesizedContainer.Construct(synthesizedContainer.ConstructedFromTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>()); } return synthesizedContainer; } internal FieldSymbol DefineCallSiteStorageSymbol(NamedTypeSymbol containerDefinition, NamedTypeSymbol delegateTypeOverMethodTypeParameters, TypeMap methodToContainerTypeParametersMap) { var fieldName = GeneratedNames.MakeDynamicCallSiteFieldName(_callSiteIdDispenser++); var delegateTypeOverContainerTypeParameters = methodToContainerTypeParametersMap.SubstituteNamedType(delegateTypeOverMethodTypeParameters); var callSiteType = _factory.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite_T); _factory.Diagnostics.ReportUseSite(callSiteType, _factory.Syntax); callSiteType = callSiteType.Construct(new[] { delegateTypeOverContainerTypeParameters }); var field = new SynthesizedFieldSymbol(containerDefinition, callSiteType, fieldName, isPublic: true, isStatic: true); _factory.AddField(containerDefinition, field); Debug.Assert(_currentDynamicCallSiteContainer is { }); return _currentDynamicCallSiteContainer.IsGenericType ? field.AsMember(_currentDynamicCallSiteContainer) : field; } internal NamedTypeSymbol? GetDelegateType( BoundExpression? loweredReceiver, RefKind receiverRefKind, ImmutableArray<BoundExpression> loweredArguments, ImmutableArray<RefKind> refKinds, BoundExpression? loweredRight, TypeSymbol resultType) { Debug.Assert(refKinds.IsDefaultOrEmpty || refKinds.Length == loweredArguments.Length); var callSiteType = _factory.WellKnownType(WellKnownType.System_Runtime_CompilerServices_CallSite); if (callSiteType.IsErrorType()) { return null; } var delegateSignature = MakeCallSiteDelegateSignature(callSiteType, loweredReceiver, loweredArguments, loweredRight, resultType); bool returnsVoid = resultType.IsVoidType(); bool hasByRefs = receiverRefKind != RefKind.None || !refKinds.IsDefaultOrEmpty; if (!hasByRefs) { var wkDelegateType = returnsVoid ? WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: delegateSignature.Length) : WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: delegateSignature.Length - 1); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = _factory.Compilation.GetWellKnownType(wkDelegateType); if (!delegateType.HasUseSiteError) { _factory.Diagnostics.AddDependencies(delegateType); return delegateType.Construct(delegateSignature); } } } RefKindVector byRefs; if (hasByRefs) { byRefs = RefKindVector.Create(1 + (loweredReceiver != null ? 1 : 0) + loweredArguments.Length + (loweredRight != null ? 1 : 0) + (returnsVoid ? 0 : 1)); int j = 1; if (loweredReceiver != null) { byRefs[j++] = getRefKind(receiverRefKind); } if (!refKinds.IsDefault) { for (int i = 0; i < refKinds.Length; i++, j++) { byRefs[j] = getRefKind(refKinds[i]); } } if (!returnsVoid) { byRefs[j++] = RefKind.None; } } else { byRefs = default(RefKindVector); } int parameterCount = delegateSignature.Length - (returnsVoid ? 0 : 1); Debug.Assert(_factory.CompilationState.ModuleBuilderOpt is { }); int generation = _factory.CompilationState.ModuleBuilderOpt.CurrentGenerationOrdinal; var synthesizedType = _factory.Compilation.AnonymousTypeManager.SynthesizeDelegate(parameterCount, byRefs, returnsVoid, generation); return synthesizedType.Construct(delegateSignature); // The distinction between by-ref kinds is ignored for dynamic call-sites. static RefKind getRefKind(RefKind refKind) => refKind == RefKind.None ? RefKind.None : RefKind.Ref; } private BoundExpression GetArgumentInfo( MethodSymbol argumentInfoFactory, BoundExpression boundArgument, string? name, RefKind refKind, bool isStaticType) { CSharpArgumentInfoFlags flags = 0; if (isStaticType) { flags |= CSharpArgumentInfoFlags.IsStaticType; } if (name != null) { flags |= CSharpArgumentInfoFlags.NamedArgument; } Debug.Assert(refKind == RefKind.None || refKind == RefKind.Ref || refKind == RefKind.Out, "unexpected refKind in dynamic"); // by-ref type doesn't trigger dynamic dispatch and it can't be a null literal => set UseCompileTimeType if (refKind == RefKind.Out) { flags |= CSharpArgumentInfoFlags.IsOut | CSharpArgumentInfoFlags.UseCompileTimeType; } else if (refKind == RefKind.Ref) { flags |= CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.UseCompileTimeType; } var argType = boundArgument.Type; // Check "literal" constant. // What the runtime binder does with this LiteralConstant flag is just to create a constant, // which is a compelling enough reason to make sure that on the production end of the binder // data, we do the inverse (i.e., use the LiteralConstant flag whenever we encounter a constant // argument. // And in fact, the bug being fixed with this change is that the compiler will consider constants // for numeric and enum conversions even if they are not literals (such as, (1-1) --> enum), but // the runtime binder didn't. So we do need to set this flag whenever we see a constant. // But the complication is that null values lose their type when they get to the runtime binder, // and so we need a way to distinguish a null constant of any given type from the null literal. // The design is simple! We use UseCompileTimeType to determine whether we care about the type of // a null constant argument, so that the null literal gets "LiteralConstant" whereas every other // constant gets "LiteralConstant | UseCompileTimeType". Because obviously UseCompileTimeType is // wrong for the null literal. // We care, because we want to prevent this from working: // // const C x = null; // class C { public void M(SomeUnrelatedReferenceType x) { } } // ... // dynamic d = new C(); d.M(x); // This will pass a null constant and the type is gone! // // as well as the alternative where x is a const null of type object. if (boundArgument.ConstantValue != null) { flags |= CSharpArgumentInfoFlags.Constant; } // Check compile time type. // See also DynamicRewriter::GenerateCallingObjectFlags. if (argType is { } && !argType.IsDynamic()) { flags |= CSharpArgumentInfoFlags.UseCompileTimeType; } return _factory.Call(null, argumentInfoFactory, _factory.Literal((int)flags), _factory.Literal(name)); } private static ImmutableArray<BoundExpression> GetCallSiteArguments(BoundExpression callSiteFieldAccess, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right) { var result = new BoundExpression[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0)]; int j = 0; result[j++] = callSiteFieldAccess; if (receiver != null) { result[j++] = receiver; } arguments.CopyTo(result, j); j += arguments.Length; if (right != null) { result[j++] = right; } return result.AsImmutableOrNull(); } private TypeSymbol[] MakeCallSiteDelegateSignature(TypeSymbol callSiteType, BoundExpression? receiver, ImmutableArray<BoundExpression> arguments, BoundExpression? right, TypeSymbol resultType) { var systemObjectType = _factory.SpecialType(SpecialType.System_Object); var result = new TypeSymbol[1 + (receiver != null ? 1 : 0) + arguments.Length + (right != null ? 1 : 0) + (resultType.IsVoidType() ? 0 : 1)]; int j = 0; // CallSite: result[j++] = callSiteType; // receiver: if (receiver != null) { result[j++] = receiver.Type ?? systemObjectType; } // argument types: for (int i = 0; i < arguments.Length; i++) { result[j++] = arguments[i].Type ?? systemObjectType; } // right hand side of an assignment: if (right != null) { result[j++] = right.Type ?? systemObjectType; } // return type: if (j < result.Length) { result[j++] = resultType ?? systemObjectType; } return result; } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Syntax/SimpleLambdaExpressionSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleLambdaExpressionSyntax { public new SimpleLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) => body is BlockSyntax block ? WithBlock(block).WithExpressionBody(null) : WithExpressionBody((ExpressionSyntax)body).WithBlock(null); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? Update(asyncKeyword, parameter, arrowToken, block, null) : Update(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public override SyntaxToken AsyncKeyword => this.Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) => WithAsyncKeyword(asyncKeyword); public new SimpleLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) => this.Update(asyncKeyword, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(SyntaxFactory.TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(this.AttributeLists, modifiers, parameter, arrowToken, block, expressionBody); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, default(SyntaxTokenList), parameter, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, block, expressionBody); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class SimpleLambdaExpressionSyntax { public new SimpleLambdaExpressionSyntax WithBody(CSharpSyntaxNode body) => body is BlockSyntax block ? WithBlock(block).WithExpressionBody(null) : WithExpressionBody((ExpressionSyntax)body).WithBlock(null); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body) => body is BlockSyntax block ? Update(asyncKeyword, parameter, arrowToken, block, null) : Update(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body); public override SyntaxToken AsyncKeyword => this.Modifiers.FirstOrDefault(SyntaxKind.AsyncKeyword); internal override AnonymousFunctionExpressionSyntax WithAsyncKeywordCore(SyntaxToken asyncKeyword) => WithAsyncKeyword(asyncKeyword); public new SimpleLambdaExpressionSyntax WithAsyncKeyword(SyntaxToken asyncKeyword) => this.Update(asyncKeyword, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(SyntaxFactory.TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public SimpleLambdaExpressionSyntax Update(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => Update(this.AttributeLists, modifiers, parameter, arrowToken, block, expressionBody); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, TokenList(asyncKeyword), parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, default(SyntaxTokenList), parameter, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, arrowToken, block, expressionBody); public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxTokenList modifiers, ParameterSyntax parameter, BlockSyntax? block, ExpressionSyntax? expressionBody) => SimpleLambdaExpression(attributeLists: default, modifiers, parameter, block, expressionBody); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Xaml/Impl/Features/Diagnostics/XamlDiagnosticSeverity.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal enum XamlDiagnosticSeverity { /// <summary> /// Represents an error. /// </summary> Error, /// <summary> /// Represent a warning. /// </summary> Warning, /// <summary> /// Represents an informational note. /// </summary> Message, /// <summary> /// Represents a hidden note. /// </summary> Hidden, /// <summary> /// Represents a hinted suggestion. /// </summary> HintedSuggestion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Diagnostics { internal enum XamlDiagnosticSeverity { /// <summary> /// Represents an error. /// </summary> Error, /// <summary> /// Represent a warning. /// </summary> Warning, /// <summary> /// Represents an informational note. /// </summary> Message, /// <summary> /// Represents a hidden note. /// </summary> Hidden, /// <summary> /// Represents a hinted suggestion. /// </summary> HintedSuggestion } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IForLoopStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IForLoopStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ForSimpleLoop() { string source = @" class C { static void Main() { int x = 3; /*<bind>*/for (int i = 0; i < 3; i = i + 1) { x = x * 3; }/*</bind>*/ System.Console.Write(""{0}"", x); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = x * 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = x * 3') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * 3') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_TrueCondition() { string source = @" class C { static void Main() { int i = 0; int j; /*<bind>*/for (j = 0; true; j = j + 1) { i = i + 1; break; }/*</bind>*/ System.Console.Write(""{0},{1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (j = 0; ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_FalseCondition() { string source = @" class C { static void Main() { int i = 0; int j; /*<bind>*/for (j = 0; false; j = j + 1) { i = i + 1; break; }/*</bind>*/ System.Console.Write(""{0},{1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (j = 0; ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithContinue() { string source = @" class C { static void Main() { int i; int j; /*<bind>*/for (i = 0, j = 0; i < 5; i = i + 1) { if (i > 2) continue; j = j + 1; }/*</bind>*/ System.Console.Write(""{0},{1}, "", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = 0, ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 2) continue;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'continue;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithBreak() { string source = @" class C { static void Main() { int i; int j; /*<bind>*/for (i = 0, j = 0; i < 5; i = i + 1) { if (i > 3) break; j = j + 1; }/*</bind>*/ System.Console.Write(""{0}, {1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = 0, ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 3) break;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithNoStatement() { string source = @" class C { static void Main() { int i = 0; /*<bind>*/for (;;) { if (i > 4) break; i = i + 2; }/*</bind>*/ System.Console.Write(""{0}"", i); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (;;) ... }') Condition: null Before(0) AtLoopBottom(0) Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 4) break;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 4') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MultipleInitializer() { string source = @" class C { static void Main() { int i = 0; int j = 0; /*<bind>*/for (i = i + 1, i = i + 1; j < 2; i = i + 2, j = j + 1) { }/*</bind>*/ System.Console.Write(""{0}"", i); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = i ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InitializerMissing() { string source = @" class C { static void Main(string[] args) { int i = 1; /*<bind>*/for (; i < 10; i = i + 1) { }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; i < ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_DecreasingIterator() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int k = 200; k > 100; k = k - 1) { }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int k ... }') Locals: Local_1: System.Int32 k Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'k > 100') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int k = 200') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int k = 200') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 k) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'k = 200') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 200') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 200) (Syntax: '200') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'k = k - 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'k = k - 1') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: 'k - 1') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MethodCall() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (Initializer(); Conditional(); Iterator()) { }/*</bind>*/ } public static int Initializer() { return 1; } public static bool Conditional() { return true; } public static int Iterator() { return 1; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (Initia ... }') Condition: IInvocationOperation (System.Boolean C.Conditional()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Conditional()') Instance Receiver: null Arguments(0) Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Initializer()') Expression: IInvocationOperation (System.Int32 C.Initializer()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Initializer()') Instance Receiver: null Arguments(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Iterator()') Expression: IInvocationOperation (System.Int32 C.Iterator()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Iterator()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MissingForBody() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 10; i < 100; i = i + 1) ;/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... = i + 1) ;') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 100') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 10') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 10') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IEmptyOperation (OperationKind.Empty, Type: null) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_Nested() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 100; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 100') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeOuterVariableInInnerLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { i = 1; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InnerLoopRefOuterIteration() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = i + 1; i < j; j = j - 1) { } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < j') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = i + 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = i + 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = i + 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i + 1') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j - 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j - 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j - 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_BreakFromNestedLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { if (j == 5) break; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (j == 5) ... break;') Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j == 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ContinueForNestedLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 1; j < 10; j = j + 1) { if ((j % 2) != 0) continue; i = i + 1; System.Console.Write(i); } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if ((j % 2) ... continue;') Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '(j % 2) != 0') Left: IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j % 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'continue;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(i);') Expression: IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_GotoForNestedLoop_1() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { goto stop; stop: j = j + 1; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IBranchOperation (BranchKind.GoTo, Label: stop) (OperationKind.Branch, Type: null) (Syntax: 'goto stop;') ILabeledOperation (Label: stop) (OperationKind.Labeled, Type: null) (Syntax: 'stop: ... j = j + 1;') Statement: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ThrowException() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10; i = i + 1) { for (int j = 0; j < 10;) { throw new System.Exception(); } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new S ... xception();') IObjectCreationOperation (Constructor: System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new System.Exception()') Arguments(0) Initializer: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ReturnInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10;) { for (int j = 0; j < 5;) { return; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;') ReturnedValue: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeValueOfInit() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0, j = 1; i < 5; i = i + 1) { j = 2; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Local_2: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0, j = 1') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0, j = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeValueOfCondition() { string source = @" class C { static void Main(string[] args) { int c = 0, x = 0; /*<bind>*/for (int i = 0; i < 50 - x; i = i + 1) { x = x + 1; c = c + 1; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 50 - x') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: '50 - x') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 50) (Syntax: '50') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = x + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = x + 1') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = c + 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'c + 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_UnreachableCode1() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (; false;) { System.Console.WriteLine(""hello""); //unreachable }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; fals ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Before(0) AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... e(""hello"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(""hello"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""hello""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"") (Syntax: '""hello""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ObjectInitAsInitializer() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (F f = new F { i = 0, s = ""abc"" }; f.i < 5; f.i = f.i + 1) { }/*</bind>*/ } } public class F { public int i; public string s; } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (F f = ... }') Locals: Local_1: F f Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'f.i < 5') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'F f = new F ... s = ""abc"" }') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'F f = new F ... s = ""abc"" }') Declarators: IVariableDeclaratorOperation (Symbol: F f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new F { ... s = ""abc"" }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new F { i ... s = ""abc"" }') IObjectCreationOperation (Constructor: F..ctor()) (OperationKind.ObjectCreation, Type: F) (Syntax: 'new F { i = ... s = ""abc"" }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: F) (Syntax: '{ i = 0, s = ""abc"" }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: F, IsImplicit) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 's = ""abc""') Left: IFieldReferenceOperation: System.String F.s (OperationKind.FieldReference, Type: System.String) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: F, IsImplicit) (Syntax: 's') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"") (Syntax: '""abc""') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'f.i = f.i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'f.i = f.i + 1') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'f.i + 1') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_DynamicInFor() { string source = @" class C { static void Main(string[] args) { dynamic d = new myFor(); /*<bind>*/for (d.Initialize(5); d.Done; d.Next()) { }/*</bind>*/ } } public class myFor { int index; int max; public void Initialize(int max) { index = 0; this.max = max; System.Console.WriteLine(""Initialize""); } public bool Done { get { System.Console.WriteLine(""Done""); return index < max; } } public void Next() { index = index + 1; System.Console.WriteLine(""Next""); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (d.Init ... }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'd.Done') Operand: IDynamicMemberReferenceOperation (Member Name: ""Done"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Done') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'd.Initialize(5)') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd.Initialize(5)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Initialize"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Initialize') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Arguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') ArgumentNames(0) ArgumentRefKinds(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'd.Next()') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd.Next()') Expression: IDynamicMemberReferenceOperation (Member Name: ""Next"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Next') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_VarInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (var i = 1; i < 5; i = i + 1) ;/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (var i ... = i + 1) ;') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var i = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var i = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IEmptyOperation (OperationKind.Empty, Type: null) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_QueryInInit() { string source = @" using System.Linq; using System.Collections.Generic; class C { static void Main(string[] args) { /*<bind>*/for (IEnumerable<string> str = from x in ""123"" let z = x.ToString() select z into w select w; ; ) { foreach (var item in str) { System.Console.WriteLine(item); } return; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (IEnume ... }') Locals: Local_1: System.Collections.Generic.IEnumerable<System.String> str Condition: null Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'IEnumerable ... select w') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IEnumerable ... select w') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.IEnumerable<System.String> str) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'str = from ... select w') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= from x in ... select w') ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x in "" ... select w') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<System.String, System.String>(this System.Collections.Generic.IEnumerable<System.String> source, System.Func<System.String, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select w') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select z') IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<<anonymous type: System.Char x, System.String z>, System.String>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> source, System.Func<<anonymous type: System.Char x, System.String z>, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select z') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = x.ToString()') IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> System.Linq.Enumerable.Select<System.Char, <anonymous type: System.Char x, System.String z>>(this System.Collections.Generic.IEnumerable<System.Char> source, System.Func<System.Char, <anonymous type: System.Char x, System.String z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in ""123""') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Char>, IsImplicit) (Syntax: 'from x in ""123""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""123"") (Syntax: '""123""') InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Char, <anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'x.ToString()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString()') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Char, IsImplicit) (Syntax: 'let z = x.T ... select w') Left: IPropertyReferenceOperation: System.Char <anonymous type: System.Char x, System.String z>.x { get; } (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'let z = x.ToString()') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IInvocationOperation (virtual System.String System.Char.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'x') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Char x, System.String z>, System.String>, IsImplicit) (Syntax: 'z') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z') ReturnedValue: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'z') Instance Receiver: IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'w') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.String, System.String>, IsImplicit) (Syntax: 'w') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'w') ReturnedValue: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.String) (Syntax: 'w') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null AtLoopBottom(0) Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'foreach (va ... }') Locals: Local_1: System.String item LoopControlVariable: IVariableDeclaratorOperation (Symbol: System.String item) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'str') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: str (OperationKind.LocalReference, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'str') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... Line(item);') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item') ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;') ReturnedValue: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_QueryInBody() { string source = @" using System.Linq; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (var item in fun()) { System.Console.WriteLine(item); } } private static IEnumerable<string> fun() { /*<bind>*/for (int i = 0; i < 5;) { return from x in ""123"" let z = x.ToString() select z into w select w; }/*</bind>*/ return null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return from ... select w;') ReturnedValue: ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x in "" ... select w') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<System.String, System.String>(this System.Collections.Generic.IEnumerable<System.String> source, System.Func<System.String, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select w') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select z') IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<<anonymous type: System.Char x, System.String z>, System.String>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> source, System.Func<<anonymous type: System.Char x, System.String z>, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select z') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = x.ToString()') IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> System.Linq.Enumerable.Select<System.Char, <anonymous type: System.Char x, System.String z>>(this System.Collections.Generic.IEnumerable<System.Char> source, System.Func<System.Char, <anonymous type: System.Char x, System.String z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in ""123""') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Char>, IsImplicit) (Syntax: 'from x in ""123""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""123"") (Syntax: '""123""') InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Char, <anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'x.ToString()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString()') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Char, IsImplicit) (Syntax: 'let z = x.T ... select w') Left: IPropertyReferenceOperation: System.Char <anonymous type: System.Char x, System.String z>.x { get; } (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'let z = x.ToString()') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IInvocationOperation (virtual System.String System.Char.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'x') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Char x, System.String z>, System.String>, IsImplicit) (Syntax: 'z') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z') ReturnedValue: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'z') Instance Receiver: IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'w') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.String, System.String>, IsImplicit) (Syntax: 'w') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'w') ReturnedValue: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.String) (Syntax: 'w') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ExpressiontreeInInit() { string source = @" class C { static void Main(string[] args) { System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x % 6; int i = 1; /*<bind>*/for (e = x => x * x; i < 5; i++) { var lambda = e.Compile(); System.Console.WriteLine(lambda(i)); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (e = x ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'e = x => x * x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e = x => x * x') Left: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'x => x * x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'x => x * x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * x') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Body: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Func<System.Int32, System.Int32> lambda IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var lambda ... .Compile();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var lambda = e.Compile()') Declarators: IVariableDeclaratorOperation (Symbol: System.Func<System.Int32, System.Int32> lambda) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'lambda = e.Compile()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= e.Compile()') IInvocationOperation ( System.Func<System.Int32, System.Int32> System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>.Compile()) (OperationKind.Invocation, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'e.Compile()') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Arguments(0) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... lambda(i));') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... (lambda(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'lambda(i)') IInvocationOperation (virtual System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'lambda(i)') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'lambda') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ExpressiontreeInIterator() { string source = @" class C { static void Main(string[] args) { System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x % 6; /*<bind>*/for (int i = 1; i < 5; e = x => x * x, i = i + 1) { var lambda = e.Compile(); System.Console.WriteLine(lambda(i)); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'e = x => x * x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e = x => x * x') Left: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'x => x * x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'x => x * x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * x') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Func<System.Int32, System.Int32> lambda IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var lambda ... .Compile();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var lambda = e.Compile()') Declarators: IVariableDeclaratorOperation (Symbol: System.Func<System.Int32, System.Int32> lambda) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'lambda = e.Compile()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= e.Compile()') IInvocationOperation ( System.Func<System.Int32, System.Int32> System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>.Compile()) (OperationKind.Invocation, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'e.Compile()') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Arguments(0) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... lambda(i));') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... (lambda(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'lambda(i)') IInvocationOperation (virtual System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'lambda(i)') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'lambda') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_CustomerTypeInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (C1 i = new C1(); i == null; i++) { }/*</bind>*/ } } public class C1 { public static C1 operator ++(C1 obj) { return obj; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (C1 i = ... l; i++) { }') Locals: Local_1: C1 i Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i == null') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: C1) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C1 i = new C1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C1 i = new C1()') Declarators: IVariableDeclaratorOperation (Symbol: C1 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = new C1()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C1()') IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'new C1()') Arguments(0) Initializer: null Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperatorMethod: C1 C1.op_Increment(C1 obj)) (OperationKind.Increment, Type: C1) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: C1) (Syntax: 'i') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PostFixIncrementInFor() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int j = i++; j < 5; ++j) { System.Console.WriteLine(j); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = i++') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = i++') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = i++') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i++') IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '++j') Expression: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++j') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(j);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'j') ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PreFixIncrementInFor() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int j = ++i; j < 5; ++j) { System.Console.WriteLine(j); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = ++i') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = ++i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = ++i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ++i') IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '++j') Expression: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++j') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(j);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'j') ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PreFixIncrementInCondition() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (int i = 0; ++i < 5;) { System.Console.WriteLine(i); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: '++i < 5') Left: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PostFixDecrementInCondition() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (int i = 0; foo(i--) > -5;) { System.Console.WriteLine(i); }/*</bind>*/ } static int foo(int x) { return x; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'foo(i--) > -5') Left: IInvocationOperation (System.Int32 Program.foo(System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'foo(i--)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'i--') IIncrementOrDecrementOperation (Postfix) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'i--') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -5) (Syntax: '-5') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InfiniteLoopVerify() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (; true;) { System.Console.WriteLine(""z""); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; true ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before(0) AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(""z"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... teLine(""z"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""z""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""z"") (Syntax: '""z""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InvalidExpression() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int k = 0, j = 0; k < 100, j > 5;/*</bind>*/ k++) { } } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'for (int k ... 100, j > 5;') Locals: Local_1: System.Int32 k Local_2: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'k < 100') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100, IsInvalid) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int k = 0, j = 0') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int k = 0, j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 k) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'k = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j > 5') Expression: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'j > 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5') Body: IEmptyOperation (OperationKind.Empty, Type: null, IsInvalid) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ConditionOutVar() { string source = @" class P { private void M() { var s = """"; /*<bind>*/for (var j = int.TryParse(s, out var i) ? i : 0; i < 10; i++) { System.Console.WriteLine($""i={i}, s={s}""); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (var j ... }') Locals: Local_1: System.Int32 j Local_2: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var j = int ... i) ? i : 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var j = int ... i) ? i : 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = int.Try ... i) ? i : 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= int.TryPa ... i) ? i : 0') IConditionalOperation (OperationKind.Conditional, Type: System.Int32) (Syntax: 'int.TryPars ... i) ? i : 0') Condition: IInvocationOperation (System.Boolean System.Int32.TryParse(System.String s, out System.Int32 result)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'int.TryPars ... out var i)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... }, s={s}"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... i}, s={s}"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '$""i={i}, s={s}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""i={i}, s={s}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'i=') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i="", IsImplicit) (Syntax: 'i=') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ', s=') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", s="", IsImplicit) (Syntax: ', s=') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{s}') Expression: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') Alignment: null FormatString: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IForLoopStatement_InvalidIterationVariableDeclaration() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int i = 0; true;) { System.Console.WriteLine(i); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(21823, "https://github.com/dotnet/roslyn/issues/21823")] [Fact] public void IForLoopStatement_CollectionLocals() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (; GetBool(out var a); GetBool(out var b)) { System.Console.WriteLine(a); }/*</bind>*/ } static bool GetBool(out int x) { throw null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; GetB ... }') ConditionLocals: Local_1: System.Int32 a Condition: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var a') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var a') ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Before(0) AtLoopBottom: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'GetBool(out var b)') Locals: Local_1: System.Int32 b IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'GetBool(out var b)') Expression: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var b') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var b') ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(a);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ForStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IForLoopStatement_MultipleIncrements() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (;; GetBool(out var j), j++) { System.Console.WriteLine(i); }/*</bind>*/ } static bool GetBool(out int x) { throw null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (;; Get ... }') Condition: null Before(0) AtLoopBottom: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'GetBool(out var j)') Locals: Local_1: System.Int32 j IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'GetBool(out var j)') Expression: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var j') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j') ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'j++') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ForStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_01() { string source = @" public sealed class MyClass { void M(int result) /*<bind>*/{ for (int i = Get<int>(out var a); Get<bool>(out var b); Get(out int c), i++) { result = b ? a : i; } }/*</bind>*/ static T Get<T>(out T x) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = Get<int>(out var a)') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = Get<int>(out var a)') Right: IInvocationOperation (System.Int32 MyClass.Get<System.Int32>(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Get<int>(out var a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var a') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var a') ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B8] Statements (0) Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [System.Boolean b] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation (System.Boolean MyClass.Get<System.Boolean>(out System.Boolean x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Get<bool>(out var b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var b') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Boolean) (Syntax: 'var b') ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B4] Entering: {R3} .locals {R3} { CaptureIds: [0] [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Jump if False (Regular) to Block[B6] ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = b ? a : i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = b ? a : i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? a : i') Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } .locals {R4} { Locals: [System.Int32 c] Block[B8] - Block Predecessors: [B7] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Get(out int c)') Expression: IInvocationOperation (System.Int32 MyClass.Get<System.Int32>(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Get(out int c)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R4} {R2} } } } Block[B9] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_02() { string source = @" public sealed class MyClass { void M(int result, int a, int b, bool c) /*<bind>*/{ for (int i = c ? a : b, j = 0; ; j++) { result = i; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [System.Int32 i] [System.Int32 j] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = c ? a : b') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = c ? a : b') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c ? a : b') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] [B6] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'j++') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B6] } Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_03() { string source = @" public sealed class MyClass { void M(int result, int a, int b, bool c, int i, int j) /*<bind>*/{ for (i = c ? a : b, j = 0; Get(out var k); ) { result = k; } }/*</bind>*/ static bool Get(out int x) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = c ? a : b') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = c ? a : b') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c ? a : b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] [B8] Statements (0) Next (Regular) Block[B7] Entering: {R2} .locals {R2} { Locals: [System.Int32 k] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation (System.Boolean MyClass.Get(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Get(out var k)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var k') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var k') ILocalReferenceOperation: k (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') InConversion: CommonConversion (Exists: True, 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} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = k;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = k') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Next (Regular) Block[B6] Leaving: {R2} } Block[B9] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_04() { string source = @" public sealed class MyClass { void M(bool result, bool a, bool b, bool c) /*<bind>*/{ for (; a ? b : c ;) { result = a; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] [B4] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = a') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B1] Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_05() { string source = @" public sealed class MyClass { void M(int result, MyClass a, MyClass b) /*<bind>*/{ for (int i = 0; i < 3 ; (a ?? b).f++) { result = i; } }/*</bind>*/ int f; } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B7] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B4] Entering: {R2} {R3} .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'a') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a') Leaving: {R3} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a') Next (Regular) Block[B7] Leaving: {R3} } Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'b') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '(a ?? b).f++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: '(a ?? b).f++') Target: IFieldReferenceOperation: System.Int32 MyClass.f (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(a ?? b).f') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a ?? b') Next (Regular) Block[B2] Leaving: {R2} } } Block[B8] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_06() { string source = @" public sealed class MyClass { void M(bool result, bool x) /*<bind>*/{ for (int i = 0; i < 3; i++) { if (x) continue; result = x; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B3] Statements (1) 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: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] } Block[B6] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_07() { string source = @" public sealed class MyClass { void M(bool result, bool x) /*<bind>*/{ for (int i = 0; i < 3; i++) { if (x) break; result = x; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block Predecessors: [B3] Statements (2) 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: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IForLoopStatement : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ForSimpleLoop() { string source = @" class C { static void Main() { int x = 3; /*<bind>*/for (int i = 0; i < 3; i = i + 1) { x = x * 3; }/*</bind>*/ System.Console.Write(""{0}"", x); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = x * 3;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = x * 3') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * 3') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_TrueCondition() { string source = @" class C { static void Main() { int i = 0; int j; /*<bind>*/for (j = 0; true; j = j + 1) { i = i + 1; break; }/*</bind>*/ System.Console.Write(""{0},{1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (j = 0; ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_FalseCondition() { string source = @" class C { static void Main() { int i = 0; int j; /*<bind>*/for (j = 0; false; j = j + 1) { i = i + 1; break; }/*</bind>*/ System.Console.Write(""{0},{1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (j = 0; ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithContinue() { string source = @" class C { static void Main() { int i; int j; /*<bind>*/for (i = 0, j = 0; i < 5; i = i + 1) { if (i > 2) continue; j = j + 1; }/*</bind>*/ System.Console.Write(""{0},{1}, "", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = 0, ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 2) continue;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: IBranchOperation (BranchKind.Continue, Label Id: 0) (OperationKind.Branch, Type: null) (Syntax: 'continue;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithBreak() { string source = @" class C { static void Main() { int i; int j; /*<bind>*/for (i = 0, j = 0; i < 5; i = i + 1) { if (i > 3) break; j = j + 1; }/*</bind>*/ System.Console.Write(""{0}, {1}"", i, j); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = 0, ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 3) break;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_WithNoStatement() { string source = @" class C { static void Main() { int i = 0; /*<bind>*/for (;;) { if (i > 4) break; i = i + 2; }/*</bind>*/ System.Console.Write(""{0}"", i); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (;;) ... }') Condition: null Before(0) AtLoopBottom(0) Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (i > 4) break;') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i > 4') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 1) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MultipleInitializer() { string source = @" class C { static void Main() { int i = 0; int j = 0; /*<bind>*/for (i = i + 1, i = i + 1; j < 2; i = i + 2, j = j + 1) { }/*</bind>*/ System.Console.Write(""{0}"", i); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (i = i ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 2') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 2') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InitializerMissing() { string source = @" class C { static void Main(string[] args) { int i = 1; /*<bind>*/for (; i < 10; i = i + 1) { }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; i < ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_DecreasingIterator() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int k = 200; k > 100; k = k - 1) { }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int k ... }') Locals: Local_1: System.Int32 k Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'k > 100') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int k = 200') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int k = 200') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 k) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'k = 200') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 200') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 200) (Syntax: '200') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'k = k - 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'k = k - 1') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: 'k - 1') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MethodCall() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (Initializer(); Conditional(); Iterator()) { }/*</bind>*/ } public static int Initializer() { return 1; } public static bool Conditional() { return true; } public static int Iterator() { return 1; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (Initia ... }') Condition: IInvocationOperation (System.Boolean C.Conditional()) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Conditional()') Instance Receiver: null Arguments(0) Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Initializer()') Expression: IInvocationOperation (System.Int32 C.Initializer()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Initializer()') Instance Receiver: null Arguments(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Iterator()') Expression: IInvocationOperation (System.Int32 C.Iterator()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Iterator()') Instance Receiver: null Arguments(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_MissingForBody() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 10; i < 100; i = i + 1) ;/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... = i + 1) ;') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 100') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 10') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 10') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 10') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 10') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IEmptyOperation (OperationKind.Empty, Type: null) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_Nested() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 100; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 100') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeOuterVariableInInnerLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { i = 1; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InnerLoopRefOuterIteration() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = i + 1; i < j; j = j - 1) { } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < j') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = i + 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = i + 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = i + 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i + 1') IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j - 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j - 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j - 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_BreakFromNestedLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { if (j == 5) break; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if (j == 5) ... break;') Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j == 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') WhenTrue: IBranchOperation (BranchKind.Break, Label Id: 3) (OperationKind.Branch, Type: null) (Syntax: 'break;') WhenFalse: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ContinueForNestedLoop() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 1; j < 10; j = j + 1) { if ((j % 2) != 0) continue; i = i + 1; System.Console.Write(i); } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (3 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IConditionalOperation (OperationKind.Conditional, Type: null) (Syntax: 'if ((j % 2) ... continue;') Condition: IBinaryOperation (BinaryOperatorKind.NotEquals) (OperationKind.Binary, Type: System.Boolean) (Syntax: '(j % 2) != 0') Left: IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j % 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') WhenTrue: IBranchOperation (BranchKind.Continue, Label Id: 2) (OperationKind.Branch, Type: null) (Syntax: 'continue;') WhenFalse: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'i = i + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Console.Write(i);') Expression: IInvocationOperation (void System.Console.Write(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Console.Write(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_GotoForNestedLoop_1() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 5; i = i + 1) { for (int j = 0; j < 10; j = j + 1) { goto stop; stop: j = j + 1; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = j + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IBranchOperation (BranchKind.GoTo, Label: stop) (OperationKind.Branch, Type: null) (Syntax: 'goto stop;') ILabeledOperation (Label: stop) (OperationKind.Labeled, Type: null) (Syntax: 'stop: ... j = j + 1;') Statement: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = j + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'j + 1') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ThrowException() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10; i = i + 1) { for (int j = 0; j < 10;) { throw new System.Exception(); } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 10') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IThrowOperation (OperationKind.Throw, Type: null) (Syntax: 'throw new S ... xception();') IObjectCreationOperation (Constructor: System.Exception..ctor()) (OperationKind.ObjectCreation, Type: System.Exception) (Syntax: 'new System.Exception()') Arguments(0) Initializer: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ReturnInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0; i < 10;) { for (int j = 0; j < 5;) { return; } }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForLoopOperation (LoopKind.For, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;') ReturnedValue: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeValueOfInit() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int i = 0, j = 1; i < 5; i = i + 1) { j = 2; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Local_2: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0, j = 1') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0, j = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'j = 2;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 2') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ChangeValueOfCondition() { string source = @" class C { static void Main(string[] args) { int c = 0, x = 0; /*<bind>*/for (int i = 0; i < 50 - x; i = i + 1) { x = x + 1; c = c + 1; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 50 - x') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Subtract) (OperationKind.Binary, Type: System.Int32) (Syntax: '50 - x') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 50) (Syntax: '50') Right: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'x = x + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'x = x + 1') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + 1') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c + 1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'c = c + 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'c + 1') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_UnreachableCode1() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (; false;) { System.Console.WriteLine(""hello""); //unreachable }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; fals ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Before(0) AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... e(""hello"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... ne(""hello"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""hello""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"") (Syntax: '""hello""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ObjectInitAsInitializer() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (F f = new F { i = 0, s = ""abc"" }; f.i < 5; f.i = f.i + 1) { }/*</bind>*/ } } public class F { public int i; public string s; } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (F f = ... }') Locals: Local_1: F f Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'f.i < 5') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'F f = new F ... s = ""abc"" }') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'F f = new F ... s = ""abc"" }') Declarators: IVariableDeclaratorOperation (Symbol: F f) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'f = new F { ... s = ""abc"" }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new F { i ... s = ""abc"" }') IObjectCreationOperation (Constructor: F..ctor()) (OperationKind.ObjectCreation, Type: F) (Syntax: 'new F { i = ... s = ""abc"" }') Arguments(0) Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: F) (Syntax: '{ i = 0, s = ""abc"" }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = 0') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'i') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: F, IsImplicit) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String) (Syntax: 's = ""abc""') Left: IFieldReferenceOperation: System.String F.s (OperationKind.FieldReference, Type: System.String) (Syntax: 's') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: F, IsImplicit) (Syntax: 's') Right: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""abc"") (Syntax: '""abc""') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'f.i = f.i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'f.i = f.i + 1') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'f.i + 1') Left: IFieldReferenceOperation: System.Int32 F.i (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'f.i') Instance Receiver: ILocalReferenceOperation: f (OperationKind.LocalReference, Type: F) (Syntax: 'f') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_DynamicInFor() { string source = @" class C { static void Main(string[] args) { dynamic d = new myFor(); /*<bind>*/for (d.Initialize(5); d.Done; d.Next()) { }/*</bind>*/ } } public class myFor { int index; int max; public void Initialize(int max) { index = 0; this.max = max; System.Console.WriteLine(""Initialize""); } public bool Done { get { System.Console.WriteLine(""Done""); return index < max; } } public void Next() { index = index + 1; System.Console.WriteLine(""Next""); } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (d.Init ... }') Condition: IUnaryOperation (UnaryOperatorKind.True) (OperationKind.Unary, Type: System.Boolean, IsImplicit) (Syntax: 'd.Done') Operand: IDynamicMemberReferenceOperation (Member Name: ""Done"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Done') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'd.Initialize(5)') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd.Initialize(5)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Initialize"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Initialize') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Arguments(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') ArgumentNames(0) ArgumentRefKinds(0) AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'd.Next()') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd.Next()') Expression: IDynamicMemberReferenceOperation (Member Name: ""Next"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'd.Next') Type Arguments(0) Instance Receiver: ILocalReferenceOperation: d (OperationKind.LocalReference, Type: dynamic) (Syntax: 'd') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_VarInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (var i = 1; i < 5; i = i + 1) ;/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (var i ... = i + 1) ;') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var i = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var i = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IEmptyOperation (OperationKind.Empty, Type: null) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_QueryInInit() { string source = @" using System.Linq; using System.Collections.Generic; class C { static void Main(string[] args) { /*<bind>*/for (IEnumerable<string> str = from x in ""123"" let z = x.ToString() select z into w select w; ; ) { foreach (var item in str) { System.Console.WriteLine(item); } return; }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (IEnume ... }') Locals: Local_1: System.Collections.Generic.IEnumerable<System.String> str Condition: null Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'IEnumerable ... select w') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'IEnumerable ... select w') Declarators: IVariableDeclaratorOperation (Symbol: System.Collections.Generic.IEnumerable<System.String> str) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'str = from ... select w') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= from x in ... select w') ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x in "" ... select w') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<System.String, System.String>(this System.Collections.Generic.IEnumerable<System.String> source, System.Func<System.String, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select w') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select z') IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<<anonymous type: System.Char x, System.String z>, System.String>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> source, System.Func<<anonymous type: System.Char x, System.String z>, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select z') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = x.ToString()') IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> System.Linq.Enumerable.Select<System.Char, <anonymous type: System.Char x, System.String z>>(this System.Collections.Generic.IEnumerable<System.Char> source, System.Func<System.Char, <anonymous type: System.Char x, System.String z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in ""123""') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Char>, IsImplicit) (Syntax: 'from x in ""123""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""123"") (Syntax: '""123""') InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Char, <anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'x.ToString()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString()') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Char, IsImplicit) (Syntax: 'let z = x.T ... select w') Left: IPropertyReferenceOperation: System.Char <anonymous type: System.Char x, System.String z>.x { get; } (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'let z = x.ToString()') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IInvocationOperation (virtual System.String System.Char.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'x') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Char x, System.String z>, System.String>, IsImplicit) (Syntax: 'z') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z') ReturnedValue: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'z') Instance Receiver: IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'w') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.String, System.String>, IsImplicit) (Syntax: 'w') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'w') ReturnedValue: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.String) (Syntax: 'w') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null AtLoopBottom(0) Body: IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 2, Exit Label Id: 3) (OperationKind.Loop, Type: null) (Syntax: 'foreach (va ... }') Locals: Local_1: System.String item LoopControlVariable: IVariableDeclaratorOperation (Symbol: System.String item) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'var') Initializer: null Collection: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'str') Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: str (OperationKind.LocalReference, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'str') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... Line(item);') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... eLine(item)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'item') ILocalReferenceOperation: item (OperationKind.LocalReference, Type: System.String) (Syntax: 'item') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) NextVariables(0) IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return;') ReturnedValue: null "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_QueryInBody() { string source = @" using System.Linq; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (var item in fun()) { System.Console.WriteLine(item); } } private static IEnumerable<string> fun() { /*<bind>*/for (int i = 0; i < 5;) { return from x in ""123"" let z = x.ToString() select z into w select w; }/*</bind>*/ return null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IReturnOperation (OperationKind.Return, Type: null) (Syntax: 'return from ... select w;') ReturnedValue: ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x in "" ... select w') Expression: IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<System.String, System.String>(this System.Collections.Generic.IEnumerable<System.String> source, System.Func<System.String, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select w') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select z') IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.Select<<anonymous type: System.Char x, System.String z>, System.String>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> source, System.Func<<anonymous type: System.Char x, System.String z>, System.String> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'select z') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = x.ToString()') IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>> System.Linq.Enumerable.Select<System.Char, <anonymous type: System.Char x, System.String z>>(this System.Collections.Generic.IEnumerable<System.Char> source, System.Func<System.Char, <anonymous type: System.Char x, System.String z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in ""123""') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Char>, IsImplicit) (Syntax: 'from x in ""123""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""123"") (Syntax: '""123""') InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Char, <anonymous type: System.Char x, System.String z>>, IsImplicit) (Syntax: 'x.ToString()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString()') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString()') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString()') ReturnedValue: IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Char, IsImplicit) (Syntax: 'let z = x.T ... select w') Left: IPropertyReferenceOperation: System.Char <anonymous type: System.Char x, System.String z>.x { get; } (OperationKind.PropertyReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char, IsImplicit) (Syntax: 'let z = x.ToString()') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.String, IsImplicit) (Syntax: 'let z = x.ToString()') Left: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String, IsImplicit) (Syntax: 'x.ToString()') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'let z = x.ToString()') Right: IInvocationOperation (virtual System.String System.Char.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()') Instance Receiver: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'x') Arguments(0) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'z') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Char x, System.String z>, System.String>, IsImplicit) (Syntax: 'z') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'z') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'z') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'z') ReturnedValue: IPropertyReferenceOperation: System.String <anonymous type: System.Char x, System.String z>.z { get; } (OperationKind.PropertyReference, Type: System.String) (Syntax: 'z') Instance Receiver: IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Char x, System.String z>, IsImplicit) (Syntax: 'z') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, 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: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'w') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.String, System.String>, IsImplicit) (Syntax: 'w') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'w') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'w') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'w') ReturnedValue: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.String) (Syntax: 'w') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ExpressiontreeInInit() { string source = @" class C { static void Main(string[] args) { System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x % 6; int i = 1; /*<bind>*/for (e = x => x * x; i < 5; i++) { var lambda = e.Compile(); System.Console.WriteLine(lambda(i)); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (e = x ... }') Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'e = x => x * x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e = x => x * x') Left: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'x => x * x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'x => x * x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * x') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Body: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Func<System.Int32, System.Int32> lambda IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var lambda ... .Compile();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var lambda = e.Compile()') Declarators: IVariableDeclaratorOperation (Symbol: System.Func<System.Int32, System.Int32> lambda) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'lambda = e.Compile()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= e.Compile()') IInvocationOperation ( System.Func<System.Int32, System.Int32> System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>.Compile()) (OperationKind.Invocation, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'e.Compile()') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Arguments(0) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... lambda(i));') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... (lambda(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'lambda(i)') IInvocationOperation (virtual System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'lambda(i)') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'lambda') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ExpressiontreeInIterator() { string source = @" class C { static void Main(string[] args) { System.Linq.Expressions.Expression<System.Func<int, int>> e = x => x % 6; /*<bind>*/for (int i = 1; i < 5; e = x => x * x, i = i + 1) { var lambda = e.Compile(); System.Console.WriteLine(lambda(i)); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 1') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 1') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'e = x => x * x') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e = x => x * x') Left: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'x => x * x') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'x => x * x') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * x') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * x') ReturnedValue: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * x') Left: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Right: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = i + 1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Body: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }') Locals: Local_1: System.Func<System.Int32, System.Int32> lambda IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var lambda ... .Compile();') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var lambda = e.Compile()') Declarators: IVariableDeclaratorOperation (Symbol: System.Func<System.Int32, System.Int32> lambda) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'lambda = e.Compile()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= e.Compile()') IInvocationOperation ( System.Func<System.Int32, System.Int32> System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>.Compile()) (OperationKind.Invocation, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'e.Compile()') Instance Receiver: ILocalReferenceOperation: e (OperationKind.LocalReference, Type: System.Linq.Expressions.Expression<System.Func<System.Int32, System.Int32>>) (Syntax: 'e') Arguments(0) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... lambda(i));') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... (lambda(i))') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'lambda(i)') IInvocationOperation (virtual System.Int32 System.Func<System.Int32, System.Int32>.Invoke(System.Int32 arg)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'lambda(i)') Instance Receiver: ILocalReferenceOperation: lambda (OperationKind.LocalReference, Type: System.Func<System.Int32, System.Int32>) (Syntax: 'lambda') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: arg) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_CustomerTypeInFor() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (C1 i = new C1(); i == null; i++) { }/*</bind>*/ } } public class C1 { public static C1 operator ++(C1 obj) { return obj; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (C1 i = ... l; i++) { }') Locals: Local_1: C1 i Condition: IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i == null') Left: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'i') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: C1) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'null') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'C1 i = new C1()') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'C1 i = new C1()') Declarators: IVariableDeclaratorOperation (Symbol: C1 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = new C1()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= new C1()') IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'new C1()') Arguments(0) Initializer: null Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperatorMethod: C1 C1.op_Increment(C1 obj)) (OperationKind.Increment, Type: C1) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: C1) (Syntax: 'i') Body: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PostFixIncrementInFor() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int j = i++; j < 5; ++j) { System.Console.WriteLine(j); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = i++') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = i++') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = i++') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= i++') IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '++j') Expression: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++j') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(j);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'j') ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PreFixIncrementInFor() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int j = ++i; j < 5; ++j) { System.Console.WriteLine(j); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int j ... }') Locals: Local_1: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'j < 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int j = ++i') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int j = ++i') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = ++i') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= ++i') IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '++j') Expression: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++j') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(j);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'j') ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PreFixIncrementInCondition() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (int i = 0; ++i < 5;) { System.Console.WriteLine(i); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: '++i < 5') Left: IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: System.Int32) (Syntax: '++i') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_PostFixDecrementInCondition() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (int i = 0; foo(i--) > -5;) { System.Console.WriteLine(i); }/*</bind>*/ } static int foo(int x) { return x; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'foo(i--) > -5') Left: IInvocationOperation (System.Int32 Program.foo(System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'foo(i--)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'i--') IIncrementOrDecrementOperation (Postfix) (OperationKind.Decrement, Type: System.Int32) (Syntax: 'i--') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Right: IUnaryOperation (UnaryOperatorKind.Minus) (OperationKind.Unary, Type: System.Int32, Constant: -5) (Syntax: '-5') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InfiniteLoopVerify() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (; true;) { System.Console.WriteLine(""z""); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; true ... }') Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before(0) AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... eLine(""z"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... teLine(""z"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '""z""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""z"") (Syntax: '""z""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_InvalidExpression() { string source = @" class C { static void Main(string[] args) { /*<bind>*/for (int k = 0, j = 0; k < 100, j > 5;/*</bind>*/ k++) { } } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'for (int k ... 100, j > 5;') Locals: Local_1: System.Int32 k Local_2: System.Int32 j Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'k < 100') Left: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100, IsInvalid) (Syntax: '100') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'int k = 0, j = 0') IVariableDeclarationOperation (2 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int k = 0, j = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 k) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'k = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: '') Expression: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid, IsImplicit) (Syntax: 'j > 5') Expression: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean, IsInvalid) (Syntax: 'j > 5') Left: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5') Body: IEmptyOperation (OperationKind.Empty, Type: null, IsInvalid) (Syntax: ';') "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17602, "https://github.com/dotnet/roslyn/issues/17602")] public void IForLoopStatement_ConditionOutVar() { string source = @" class P { private void M() { var s = """"; /*<bind>*/for (var j = int.TryParse(s, out var i) ? i : 0; i < 10; i++) { System.Console.WriteLine($""i={i}, s={s}""); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (var j ... }') Locals: Local_1: System.Int32 j Local_2: System.Int32 i Condition: IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 10') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsImplicit) (Syntax: 'var j = int ... i) ? i : 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var j = int ... i) ? i : 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 j) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'j = int.Try ... i) ? i : 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= int.TryPa ... i) ? i : 0') IConditionalOperation (OperationKind.Conditional, Type: System.Int32) (Syntax: 'int.TryPars ... i) ? i : 0') Condition: IInvocationOperation (System.Boolean System.Int32.TryParse(System.String s, out System.Int32 result)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'int.TryPars ... out var i)') Instance Receiver: null Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: 's') ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: result) (OperationKind.Argument, Type: null) (Syntax: 'out var i') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i') ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) WhenTrue: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... }, s={s}"");') Expression: IInvocationOperation (void System.Console.WriteLine(System.String value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... i}, s={s}"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '$""i={i}, s={s}""') IInterpolatedStringOperation (OperationKind.InterpolatedString, Type: System.String) (Syntax: '$""i={i}, s={s}""') Parts(4): IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: 'i=') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""i="", IsImplicit) (Syntax: 'i=') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{i}') Expression: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Alignment: null FormatString: null IInterpolatedStringTextOperation (OperationKind.InterpolatedStringText, Type: null) (Syntax: ', s=') Text: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "", s="", IsImplicit) (Syntax: ', s=') IInterpolationOperation (OperationKind.Interpolation, Type: null) (Syntax: '{s}') Expression: ILocalReferenceOperation: s (OperationKind.LocalReference, Type: System.String) (Syntax: 's') Alignment: null FormatString: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IForLoopStatement_InvalidIterationVariableDeclaration() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (int i = 0; true;) { System.Console.WriteLine(i); }/*</bind>*/ } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'for (int i ... }') Locals: Local_1: System.Int32 i Condition: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Before: IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid, IsImplicit) (Syntax: 'int i = 0') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'int i = 0') Declarators: IVariableDeclaratorOperation (Symbol: System.Int32 i) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'i = 0') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= 0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Initializer: null AtLoopBottom(0) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; VerifyOperationTreeForTest<ForStatementSyntax>(source, expectedOperationTree); } [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(21823, "https://github.com/dotnet/roslyn/issues/21823")] [Fact] public void IForLoopStatement_CollectionLocals() { string source = @" class Program { static void Main(string[] args) { /*<bind>*/for (; GetBool(out var a); GetBool(out var b)) { System.Console.WriteLine(a); }/*</bind>*/ } static bool GetBool(out int x) { throw null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (; GetB ... }') ConditionLocals: Local_1: System.Int32 a Condition: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var a') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var a') ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Before(0) AtLoopBottom: IBlockOperation (1 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'GetBool(out var b)') Locals: Local_1: System.Int32 b IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'GetBool(out var b)') Expression: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var b') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var b') ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(a);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'a') ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ForStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void IForLoopStatement_MultipleIncrements() { string source = @" class Program { static void Main(string[] args) { int i = 0; /*<bind>*/for (;; GetBool(out var j), j++) { System.Console.WriteLine(i); }/*</bind>*/ } static bool GetBool(out int x) { throw null; } } "; string expectedOperationTree = @" IForLoopOperation (LoopKind.For, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null) (Syntax: 'for (;; Get ... }') Condition: null Before(0) AtLoopBottom: IBlockOperation (2 statements, 1 locals) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'GetBool(out var j)') Locals: Local_1: System.Int32 j IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'GetBool(out var j)') Expression: IInvocationOperation (System.Boolean Program.GetBool(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'GetBool(out var j)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var j') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var j') ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'j++') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Body: IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... iteLine(i);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(i)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: 'i') ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ForStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_01() { string source = @" public sealed class MyClass { void M(int result) /*<bind>*/{ for (int i = Get<int>(out var a); Get<bool>(out var b); Get(out int c), i++) { result = b ? a : i; } }/*</bind>*/ static T Get<T>(out T x) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] [System.Int32 a] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = Get<int>(out var a)') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = Get<int>(out var a)') Right: IInvocationOperation (System.Int32 MyClass.Get<System.Int32>(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Get<int>(out var a)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var a') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var a') ILocalReferenceOperation: a (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B8] Statements (0) Next (Regular) Block[B3] Entering: {R2} .locals {R2} { Locals: [System.Boolean b] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation (System.Boolean MyClass.Get<System.Boolean>(out System.Boolean x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Get<bool>(out var b)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var b') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Boolean) (Syntax: 'var b') ILocalReferenceOperation: b (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Leaving: {R2} {R1} Next (Regular) Block[B4] Entering: {R3} .locals {R3} { CaptureIds: [0] [1] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Jump if False (Regular) to Block[B6] ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: ILocalReferenceOperation: a (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = b ? a : i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = b ? a : i') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? a : i') Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } .locals {R4} { Locals: [System.Int32 c] Block[B8] - Block Predecessors: [B7] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Get(out int c)') Expression: IInvocationOperation (System.Int32 MyClass.Get<System.Int32>(out System.Int32 x)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'Get(out int c)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out int c') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int c') ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'c') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] Leaving: {R4} {R2} } } } Block[B9] - Exit Predecessors: [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_02() { string source = @" public sealed class MyClass { void M(int result, int a, int b, bool c) /*<bind>*/{ for (int i = c ? a : b, j = 0; ; j++) { result = i; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { Locals: [System.Int32 i] [System.Int32 j] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = c ? a : b') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = c ? a : b') Right: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c ? a : b') Next (Regular) Block[B5] Leaving: {R2} } Block[B5] - Block Predecessors: [B4] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'j = 0') Left: ILocalReferenceOperation: j (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'j = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] [B6] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'j++') Target: ILocalReferenceOperation: j (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'j') Next (Regular) Block[B6] } Block[B7] - Exit [UnReachable] Predecessors (0) Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_03() { string source = @" public sealed class MyClass { void M(int result, int a, int b, bool c, int i, int j) /*<bind>*/{ for (i = c ? a : b, j = 0; Get(out var k); ) { result = k; } }/*</bind>*/ static bool Get(out int x) { throw null; } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i = c ? a : b') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'i = c ? a : b') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'c ? a : b') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Block Predecessors: [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'j = 0') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'j = 0') Left: IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] [B8] Statements (0) Next (Regular) Block[B7] Entering: {R2} .locals {R2} { Locals: [System.Int32 k] Block[B7] - Block Predecessors: [B6] Statements (0) Jump if False (Regular) to Block[B9] IInvocationOperation (System.Boolean MyClass.Get(out System.Int32 x)) (OperationKind.Invocation, Type: System.Boolean) (Syntax: 'Get(out var k)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'out var k') IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var k') ILocalReferenceOperation: k (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') InConversion: CommonConversion (Exists: True, 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} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = k;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = k') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') Next (Regular) Block[B6] Leaving: {R2} } Block[B9] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_04() { string source = @" public sealed class MyClass { void M(bool result, bool a, bool b, bool c) /*<bind>*/{ for (; a ? b : c ;) { result = a; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] [B4] Statements (0) Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'c') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = a;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = a') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Right: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B1] Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_05() { string source = @" public sealed class MyClass { void M(int result, MyClass a, MyClass b) /*<bind>*/{ for (int i = 0; i < 3 ; (a ?? b).f++) { result = i; } }/*</bind>*/ int f; } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B7] Statements (0) Jump if False (Regular) to Block[B8] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'result = i') Left: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'result') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B4] Entering: {R2} {R3} .locals {R2} { CaptureIds: [1] .locals {R3} { CaptureIds: [0] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'a') Jump if True (Regular) to Block[B6] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a') Leaving: {R3} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a') Next (Regular) Block[B7] Leaving: {R3} } Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: MyClass) (Syntax: 'b') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: '(a ?? b).f++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: '(a ?? b).f++') Target: IFieldReferenceOperation: System.Int32 MyClass.f (OperationKind.FieldReference, Type: System.Int32) (Syntax: '(a ?? b).f') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: MyClass, IsImplicit) (Syntax: 'a ?? b') Next (Regular) Block[B2] Leaving: {R2} } } Block[B8] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_06() { string source = @" public sealed class MyClass { void M(bool result, bool x) /*<bind>*/{ for (int i = 0; i < 3; i++) { if (x) continue; result = x; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B5] Statements (0) Jump if False (Regular) to Block[B6] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B3] Statements (1) 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: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] } Block[B6] - Exit Predecessors: [B2] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void ForFlow_07() { string source = @" public sealed class MyClass { void M(bool result, bool x) /*<bind>*/{ for (int i = 0; i < 3; i++) { if (x) break; result = x; } }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 i] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Left: ILocalReferenceOperation: i (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'i = 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] [B4] Statements (0) Jump if False (Regular) to Block[B5] IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 3') Left: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Leaving: {R1} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') Next (Regular) Block[B5] Leaving: {R1} Block[B4] - Block Predecessors: [B3] Statements (2) 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: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'x') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'i++') Expression: IIncrementOrDecrementOperation (Postfix) (OperationKind.Increment, Type: System.Int32) (Syntax: 'i++') Target: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B2] } Block[B5] - Exit Predecessors: [B2] [B3] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/xlf/CodeFixesResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">Leere Zeile nach Block hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">Beide hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">Standardfall hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">Dateiheader hinzufügen</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">Namensverletzung beheben: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">Alle Vorkommen korrigieren in</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">Zusätzliche Leerzeilen entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">Überflüssige Zuweisung entfernen</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">Issues unterdrücken oder konfigurieren</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">Unterdrückungsformat aktualisieren</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">Ausschussvariable "_" verwenden</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">Verworfene lokale Variable verwenden</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../CodeFixesResources.resx"> <body> <trans-unit id="Add_blank_line_after_block"> <source>Add blank line after block</source> <target state="translated">Leere Zeile nach Block hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_both"> <source>Add both</source> <target state="translated">Beide hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_default_case"> <source>Add default case</source> <target state="translated">Standardfall hinzufügen</target> <note /> </trans-unit> <trans-unit id="Add_file_header"> <source>Add file header</source> <target state="translated">Dateiheader hinzufügen</target> <note /> </trans-unit> <trans-unit id="Fix_Name_Violation_colon_0"> <source>Fix Name Violation: {0}</source> <target state="translated">Namensverletzung beheben: {0}</target> <note /> </trans-unit> <trans-unit id="Fix_all_occurrences_in"> <source>Fix all occurrences in</source> <target state="translated">Alle Vorkommen korrigieren in</target> <note /> </trans-unit> <trans-unit id="Remove_extra_blank_lines"> <source>Remove extra blank lines</source> <target state="translated">Zusätzliche Leerzeilen entfernen</target> <note /> </trans-unit> <trans-unit id="Remove_redundant_assignment"> <source>Remove redundant assignment</source> <target state="translated">Überflüssige Zuweisung entfernen</target> <note /> </trans-unit> <trans-unit id="Suppress_or_Configure_issues"> <source>Suppress or Configure issues</source> <target state="translated">Issues unterdrücken oder konfigurieren</target> <note /> </trans-unit> <trans-unit id="Update_suppression_format"> <source>Update suppression format</source> <target state="translated">Unterdrückungsformat aktualisieren</target> <note /> </trans-unit> <trans-unit id="Use_discard_underscore"> <source>Use discard '_'</source> <target state="translated">Ausschussvariable "_" verwenden</target> <note /> </trans-unit> <trans-unit id="Use_discarded_local"> <source>Use discarded local</source> <target state="translated">Verworfene lokale Variable verwenden</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Test/Symbol/Compilation/CSharpCompilationOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class CSharpCompilationOptionsExtensions { public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected) { options.Errors.Verify(expected); } } public class CSharpCompilationOptionsTests : CSharpTestBase { /// <summary> /// Using an instance of <see cref="CSharpCompilationOptions"/>, tests a property in <see cref="CompilationOptions"/> , even it is hidden by <see cref="CSharpCompilationOptions"/>. /// </summary> private void TestHiddenProperty<T>( Func<CompilationOptions, T, CompilationOptions> factory, Func<CompilationOptions, T> getter, T validNonDefaultValue) { TestPropertyGeneric(new CSharpCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue); } private static void TestPropertyGeneric<TOptions, T>(TOptions oldOptions, Func<TOptions, T, TOptions> factory, Func<TOptions, T> getter, T validNonDefaultValue) where TOptions : CompilationOptions { var validDefaultValue = getter(oldOptions); // we need non-default value to test Equals and GetHashCode Assert.NotEqual(validNonDefaultValue, validDefaultValue); // check that the assigned value can be read: var newOpt1 = factory(oldOptions, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(newOpt1)); Assert.Equal(0, newOpt1.Errors.Length); // check that creating new options with the same value yields the same options instance: var newOpt1_alias = factory(newOpt1, validNonDefaultValue); Assert.Same(newOpt1_alias, newOpt1); // check that Equals and GetHashCode work var newOpt2 = factory(oldOptions, validNonDefaultValue); Assert.False(newOpt1.Equals(oldOptions)); Assert.True(newOpt1.Equals(newOpt2)); Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode()); // test default(T): Assert.NotNull(factory(oldOptions, default(T))); } [Fact] public void ShadowInvariants() { TestHiddenProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary); TestHiddenProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll"); TestHiddenProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar"); TestHiddenProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>"); TestHiddenProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release); TestHiddenProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true); TestHiddenProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo"); TestHiddenProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo"); TestHiddenProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create<byte>(0, 1, 2, 3)); TestHiddenProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true); TestHiddenProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium); TestHiddenProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress); TestHiddenProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions, new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary()); TestHiddenProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true); TestHiddenProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false); TestHiddenProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null)); TestHiddenProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver()); TestHiddenProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy())); TestHiddenProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider()); } private void TestProperty<T>( Func<CSharpCompilationOptions, T, CSharpCompilationOptions> factory, Func<CSharpCompilationOptions, T> getter, T validNonDefaultValue) { TestPropertyGeneric(new CSharpCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue); } [Fact] public void Invariants() { TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary); TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll"); TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar"); TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>"); TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B")); TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release); TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true); TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true); TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo"); TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo"); TestProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create<byte>(0, 1, 2, 3)); TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true); TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium); TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress); TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3); TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions, new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary()); TestProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true); TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false); TestProperty((old, value) => old.WithCurrentLocalTime(value), opt => opt.CurrentLocalTime, new DateTime(2005, 1, 1)); TestProperty((old, value) => old.WithDebugPlusMode(value), opt => opt.DebugPlusMode, true); TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null)); TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver()); TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy())); TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider()); TestProperty((old, value) => old.WithTopLevelBinderFlags(value), opt => opt.TopLevelBinderFlags, BinderFlags.IgnoreCorLibraryDuplicatedTypes); TestProperty((old, value) => old.WithMetadataImportOptions(value), opt => opt.MetadataImportOptions, MetadataImportOptions.Internal); TestProperty((old, value) => old.WithReferencesSupersedeLowerVersions(value), opt => opt.ReferencesSupersedeLowerVersions, true); TestProperty((old, value) => old.WithNullableContextOptions(value), opt => opt.NullableContextOptions, NullableContextOptions.Enable); } [Fact] public void WithXxx() { new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(null).VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah\0goo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah\0goo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MaxValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MaxValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); var defaultWarnings = new CSharpCompilationOptions(OutputKind.ConsoleApplication); Assert.Equal(ReportDiagnostic.Default, defaultWarnings.GeneralDiagnosticOption); Assert.Equal(CodeAnalysis.Diagnostic.DefaultWarningLevel, defaultWarnings.WarningLevel); Assert.Equal(ReportDiagnostic.Error, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Error).GeneralDiagnosticOption); Assert.Equal(ReportDiagnostic.Default, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Default).GeneralDiagnosticOption); } [Fact] public void WithUsings() { var actual1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new[] { "A", "B" }).Usings; Assert.True(actual1.SequenceEqual(new[] { "A", "B" })); var actual2 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(Enumerable.Repeat("A", 1)).Usings; Assert.True(actual2.SequenceEqual(Enumerable.Repeat("A", 1))); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings(null).Usings.Count()); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings((string[])null).Usings.Count()); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "blah\0goo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0goo")); } [Fact] public void WithWarnings() { var warnings = new Dictionary<string, ReportDiagnostic> { { MessageProvider.Instance.GetIdForErrorCode(1), ReportDiagnostic.Error }, { MessageProvider.Instance.GetIdForErrorCode(2), ReportDiagnostic.Suppress }, { MessageProvider.Instance.GetIdForErrorCode(3), ReportDiagnostic.Warn } }; Assert.Equal(3, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(warnings).SpecificDiagnosticOptions.Count); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(null).SpecificDiagnosticOptions.Count); Assert.Equal(1, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(1).WarningLevel); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(-1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(5).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(int.MaxValue).VerifyErrors(); } [Fact] public void WithModuleName() { // ModuleName Assert.Null(TestOptions.ReleaseDll.WithModuleName(null).ModuleName); TestOptions.ReleaseDll.WithModuleName("").VerifyErrors( // error CS7087: Invalid module name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\0a").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\uD800b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\\b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a/b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a:b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); } [Fact] public void ConstructorValidation() { new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "blah\0goo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0goo")); Assert.Equal("Script", new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: null).ScriptClassName); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "blah\0goo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "blah\0goo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: (Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: -1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: 5).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: int.MaxValue).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); } /// <summary> /// If this test fails, please update the <see cref="CSharpCompilationOptions.GetHashCode"/> /// and <see cref="CSharpCompilationOptions.Equals(CSharpCompilationOptions)"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(CSharpCompilationOptions), "Language", "AllowUnsafe", "Usings", "TopLevelBinderFlags", "NullableContextOptions"); } [Fact] public void TestEqualitySemantics() { CSharpCompilationOptions first = CreateCSharpCompilationOptions(); CSharpCompilationOptions second = CreateCSharpCompilationOptions(); Assert.Equal(first, second); Assert.Equal(first.GetHashCode(), second.GetHashCode()); } private static CSharpCompilationOptions CreateCSharpCompilationOptions() { string moduleName = null; string mainTypeName = null; string scriptClassName = null; IEnumerable<string> usings = null; OptimizationLevel optimizationLevel = OptimizationLevel.Debug; bool checkOverflow = false; bool allowUnsafe = false; string cryptoKeyContainer = null; string cryptoKeyFile = null; ImmutableArray<byte> cryptoPublicKey = default(ImmutableArray<byte>); bool? delaySign = null; Platform platform = 0; ReportDiagnostic generalDiagnosticOption = 0; int warningLevel = 0; IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions = null; bool concurrentBuild = false; bool deterministic = false; DateTime currentLocalTime = default(DateTime); bool debugPlusMode = false; XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null); SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray<string>.Empty, null); SyntaxTreeOptionsProvider syntaxTreeOptionsProvider = null; MetadataReferenceResolver metadataReferenceResolver = new MetadataReferenceResolverWithEquality(); AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality StrongNameProvider strongNameProvider = new DesktopStrongNameProvider(); MetadataImportOptions metadataImportOptions = 0; bool referencesSupersedeLowerVersions = false; bool reportSuppressedDiagnostics = false; var topLevelBinderFlags = BinderFlags.None; var publicSign = false; NullableContextOptions nullableContextOptions = NullableContextOptions.Disable; return new CSharpCompilationOptions(OutputKind.ConsoleApplication, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, currentLocalTime, debugPlusMode, xmlReferenceResolver, sourceReferenceResolver, syntaxTreeOptionsProvider, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions, publicSign, topLevelBinderFlags, nullableContextOptions); } private sealed class MetadataReferenceResolverWithEquality : MetadataReferenceResolver { public override bool Equals(object other) => true; public override int GetHashCode() => 1; public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [Fact] public void WithCryptoPublicKey() { var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication); Assert.Equal(ImmutableArray<byte>.Empty, options.CryptoPublicKey); Assert.Equal(ImmutableArray<byte>.Empty, options.WithCryptoPublicKey(default(ImmutableArray<byte>)).CryptoPublicKey); Assert.Same(options, options.WithCryptoPublicKey(default(ImmutableArray<byte>))); Assert.Same(options, options.WithCryptoPublicKey(ImmutableArray<byte>.Empty)); } [Fact] public void TestWithNullable() { Assert.Equal(NullableContextOptions.Disable, new CSharpCompilationOptions(OutputKind.ConsoleApplication).NullableContextOptions); var values = (NullableContextOptions[])System.Enum.GetValues(typeof(NullableContextOptions)); var options = new CSharpCompilationOptions[values.Length]; for (int i = 0; i < values.Length; i++) { options[i] = new CSharpCompilationOptions(OutputKind.ConsoleApplication, nullableContextOptions: values[i]); Assert.Equal(values[i], options[i].NullableContextOptions); } for (int i = 0; i < values.Length; i++) { var oldOptions = options[i]; for (int j = 0; j < values.Length; j++) { var newOptions = oldOptions.WithNullableContextOptions(values[j]); Assert.Equal(values[j], newOptions.NullableContextOptions); Assert.Equal(options[j], newOptions); Assert.Equal(options[j].GetHashCode(), newOptions.GetHashCode()); if (i == j) { Assert.Same(oldOptions, newOptions); } else { Assert.NotSame(oldOptions, newOptions); Assert.NotEqual(oldOptions, newOptions); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class CSharpCompilationOptionsExtensions { public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected) { options.Errors.Verify(expected); } } public class CSharpCompilationOptionsTests : CSharpTestBase { /// <summary> /// Using an instance of <see cref="CSharpCompilationOptions"/>, tests a property in <see cref="CompilationOptions"/> , even it is hidden by <see cref="CSharpCompilationOptions"/>. /// </summary> private void TestHiddenProperty<T>( Func<CompilationOptions, T, CompilationOptions> factory, Func<CompilationOptions, T> getter, T validNonDefaultValue) { TestPropertyGeneric(new CSharpCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue); } private static void TestPropertyGeneric<TOptions, T>(TOptions oldOptions, Func<TOptions, T, TOptions> factory, Func<TOptions, T> getter, T validNonDefaultValue) where TOptions : CompilationOptions { var validDefaultValue = getter(oldOptions); // we need non-default value to test Equals and GetHashCode Assert.NotEqual(validNonDefaultValue, validDefaultValue); // check that the assigned value can be read: var newOpt1 = factory(oldOptions, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(newOpt1)); Assert.Equal(0, newOpt1.Errors.Length); // check that creating new options with the same value yields the same options instance: var newOpt1_alias = factory(newOpt1, validNonDefaultValue); Assert.Same(newOpt1_alias, newOpt1); // check that Equals and GetHashCode work var newOpt2 = factory(oldOptions, validNonDefaultValue); Assert.False(newOpt1.Equals(oldOptions)); Assert.True(newOpt1.Equals(newOpt2)); Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode()); // test default(T): Assert.NotNull(factory(oldOptions, default(T))); } [Fact] public void ShadowInvariants() { TestHiddenProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary); TestHiddenProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll"); TestHiddenProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar"); TestHiddenProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>"); TestHiddenProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release); TestHiddenProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true); TestHiddenProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo"); TestHiddenProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo"); TestHiddenProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create<byte>(0, 1, 2, 3)); TestHiddenProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true); TestHiddenProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium); TestHiddenProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress); TestHiddenProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions, new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary()); TestHiddenProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true); TestHiddenProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false); TestHiddenProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null)); TestHiddenProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver()); TestHiddenProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy())); TestHiddenProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider()); } private void TestProperty<T>( Func<CSharpCompilationOptions, T, CSharpCompilationOptions> factory, Func<CSharpCompilationOptions, T> getter, T validNonDefaultValue) { TestPropertyGeneric(new CSharpCompilationOptions(OutputKind.ConsoleApplication), factory, getter, validNonDefaultValue); } [Fact] public void Invariants() { TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary); TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "goo.dll"); TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Goo.Bar"); TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>"); TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B")); TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release); TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true); TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true); TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "goo"); TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "goo"); TestProperty((old, value) => old.WithCryptoPublicKey(value), opt => opt.CryptoPublicKey, ImmutableArray.Create<byte>(0, 1, 2, 3)); TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true); TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium); TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress); TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3); TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions, new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary()); TestProperty((old, value) => old.WithReportSuppressedDiagnostics(value), opt => opt.ReportSuppressedDiagnostics, true); TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false); TestProperty((old, value) => old.WithCurrentLocalTime(value), opt => opt.CurrentLocalTime, new DateTime(2005, 1, 1)); TestProperty((old, value) => old.WithDebugPlusMode(value), opt => opt.DebugPlusMode, true); TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null)); TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new TestMetadataReferenceResolver()); TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy())); TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider()); TestProperty((old, value) => old.WithTopLevelBinderFlags(value), opt => opt.TopLevelBinderFlags, BinderFlags.IgnoreCorLibraryDuplicatedTypes); TestProperty((old, value) => old.WithMetadataImportOptions(value), opt => opt.MetadataImportOptions, MetadataImportOptions.Internal); TestProperty((old, value) => old.WithReferencesSupersedeLowerVersions(value), opt => opt.ReferencesSupersedeLowerVersions, true); TestProperty((old, value) => old.WithNullableContextOptions(value), opt => opt.NullableContextOptions, NullableContextOptions.Enable); } [Fact] public void WithXxx() { new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(null).VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah\0goo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah\0goo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MaxValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MaxValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); var defaultWarnings = new CSharpCompilationOptions(OutputKind.ConsoleApplication); Assert.Equal(ReportDiagnostic.Default, defaultWarnings.GeneralDiagnosticOption); Assert.Equal(CodeAnalysis.Diagnostic.DefaultWarningLevel, defaultWarnings.WarningLevel); Assert.Equal(ReportDiagnostic.Error, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Error).GeneralDiagnosticOption); Assert.Equal(ReportDiagnostic.Default, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Default).GeneralDiagnosticOption); } [Fact] public void WithUsings() { var actual1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new[] { "A", "B" }).Usings; Assert.True(actual1.SequenceEqual(new[] { "A", "B" })); var actual2 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(Enumerable.Repeat("A", 1)).Usings; Assert.True(actual2.SequenceEqual(Enumerable.Repeat("A", 1))); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings(null).Usings.Count()); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings((string[])null).Usings.Count()); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "blah\0goo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0goo")); } [Fact] public void WithWarnings() { var warnings = new Dictionary<string, ReportDiagnostic> { { MessageProvider.Instance.GetIdForErrorCode(1), ReportDiagnostic.Error }, { MessageProvider.Instance.GetIdForErrorCode(2), ReportDiagnostic.Suppress }, { MessageProvider.Instance.GetIdForErrorCode(3), ReportDiagnostic.Warn } }; Assert.Equal(3, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(warnings).SpecificDiagnosticOptions.Count); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(null).SpecificDiagnosticOptions.Count); Assert.Equal(1, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(1).WarningLevel); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(-1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(5).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(int.MaxValue).VerifyErrors(); } [Fact] public void WithModuleName() { // ModuleName Assert.Null(TestOptions.ReleaseDll.WithModuleName(null).ModuleName); TestOptions.ReleaseDll.WithModuleName("").VerifyErrors( // error CS7087: Invalid module name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\0a").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\uD800b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a\\b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a/b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); TestOptions.ReleaseDll.WithModuleName("a:b").VerifyErrors( // error CS7087: Invalid module name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadModuleName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); } [Fact] public void ConstructorValidation() { new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { null }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'null'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "blah\0goo" }).VerifyErrors( // error CS7088: Invalid 'Usings' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0goo")); Assert.Equal("Script", new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: null).ScriptClassName); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "blah\0goo").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "").VerifyErrors( // error CS7088: Invalid 'ScriptClassName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "")); Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: null).Errors.Length); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "blah\0goo").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: 'blah\0goo'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0goo")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "").VerifyErrors( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "")); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString())); new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MaxValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MinValue).VerifyErrors( // error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: (Platform)Int32.MinValue).VerifyErrors( // error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64 Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString())); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: -1).VerifyErrors( // error CS7088: Invalid 'WarningLevel' value: '-1'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1")); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: 5).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: int.MaxValue).VerifyErrors(); new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(); new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, platform: Platform.AnyCpu32BitPreferred).VerifyErrors( Diagnostic(ErrorCode.ERR_BadPrefer32OnLib)); } /// <summary> /// If this test fails, please update the <see cref="CSharpCompilationOptions.GetHashCode"/> /// and <see cref="CSharpCompilationOptions.Equals(CSharpCompilationOptions)"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(CSharpCompilationOptions), "Language", "AllowUnsafe", "Usings", "TopLevelBinderFlags", "NullableContextOptions"); } [Fact] public void TestEqualitySemantics() { CSharpCompilationOptions first = CreateCSharpCompilationOptions(); CSharpCompilationOptions second = CreateCSharpCompilationOptions(); Assert.Equal(first, second); Assert.Equal(first.GetHashCode(), second.GetHashCode()); } private static CSharpCompilationOptions CreateCSharpCompilationOptions() { string moduleName = null; string mainTypeName = null; string scriptClassName = null; IEnumerable<string> usings = null; OptimizationLevel optimizationLevel = OptimizationLevel.Debug; bool checkOverflow = false; bool allowUnsafe = false; string cryptoKeyContainer = null; string cryptoKeyFile = null; ImmutableArray<byte> cryptoPublicKey = default(ImmutableArray<byte>); bool? delaySign = null; Platform platform = 0; ReportDiagnostic generalDiagnosticOption = 0; int warningLevel = 0; IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions = null; bool concurrentBuild = false; bool deterministic = false; DateTime currentLocalTime = default(DateTime); bool debugPlusMode = false; XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null); SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray<string>.Empty, null); SyntaxTreeOptionsProvider syntaxTreeOptionsProvider = null; MetadataReferenceResolver metadataReferenceResolver = new MetadataReferenceResolverWithEquality(); AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality StrongNameProvider strongNameProvider = new DesktopStrongNameProvider(); MetadataImportOptions metadataImportOptions = 0; bool referencesSupersedeLowerVersions = false; bool reportSuppressedDiagnostics = false; var topLevelBinderFlags = BinderFlags.None; var publicSign = false; NullableContextOptions nullableContextOptions = NullableContextOptions.Disable; return new CSharpCompilationOptions(OutputKind.ConsoleApplication, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, usings, optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, currentLocalTime, debugPlusMode, xmlReferenceResolver, sourceReferenceResolver, syntaxTreeOptionsProvider, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions, publicSign, topLevelBinderFlags, nullableContextOptions); } private sealed class MetadataReferenceResolverWithEquality : MetadataReferenceResolver { public override bool Equals(object other) => true; public override int GetHashCode() => 1; public override ImmutableArray<PortableExecutableReference> ResolveReference(string reference, string baseFilePath, MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [Fact] public void WithCryptoPublicKey() { var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication); Assert.Equal(ImmutableArray<byte>.Empty, options.CryptoPublicKey); Assert.Equal(ImmutableArray<byte>.Empty, options.WithCryptoPublicKey(default(ImmutableArray<byte>)).CryptoPublicKey); Assert.Same(options, options.WithCryptoPublicKey(default(ImmutableArray<byte>))); Assert.Same(options, options.WithCryptoPublicKey(ImmutableArray<byte>.Empty)); } [Fact] public void TestWithNullable() { Assert.Equal(NullableContextOptions.Disable, new CSharpCompilationOptions(OutputKind.ConsoleApplication).NullableContextOptions); var values = (NullableContextOptions[])System.Enum.GetValues(typeof(NullableContextOptions)); var options = new CSharpCompilationOptions[values.Length]; for (int i = 0; i < values.Length; i++) { options[i] = new CSharpCompilationOptions(OutputKind.ConsoleApplication, nullableContextOptions: values[i]); Assert.Equal(values[i], options[i].NullableContextOptions); } for (int i = 0; i < values.Length; i++) { var oldOptions = options[i]; for (int j = 0; j < values.Length; j++) { var newOptions = oldOptions.WithNullableContextOptions(values[j]); Assert.Equal(values[j], newOptions.NullableContextOptions); Assert.Equal(options[j], newOptions); Assert.Equal(options[j].GetHashCode(), newOptions.GetHashCode()); if (i == j) { Assert.Same(oldOptions, newOptions); } else { Assert.NotSame(oldOptions, newOptions); Assert.NotEqual(oldOptions, newOptions); } } } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/SolutionCrawler/Extensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class Extensions { public static string ToBase64(this string data) { // Write out the message in base64, since it may contain // user code that can't be represented in xml. (see // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=578059) return Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); } public static string DecodeBase64(this string data) { var bytes = Convert.FromBase64String(data); return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal static class Extensions { public static string ToBase64(this string data) { // Write out the message in base64, since it may contain // user code that can't be represented in xml. (see // http://vstfdevdiv:8080/web/wi.aspx?pcguid=22f9acc9-569a-41ff-b6ac-fac1b6370209&id=578059) return Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); } public static string DecodeBase64(this string data) { var bytes = Convert.FromBase64String(data); return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/WithKeywordRecommenderTests.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 WithKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Exit | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Continue | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Continue | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Exit | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitInsideLambdaInsideWithBlockTest() VerifyRecommendationsMissing(<MethodBody> While Dim x = Sub() Exit | End Sub Loop </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterExitInsideWhileLoopInsideLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() With x Exit | Loop End Sub </MethodBody>, "With") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class WithKeywordRecommenderTests Inherits RecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithInLambdaTest() VerifyRecommendationsContain(<MethodBody> Dim x = Sub() | End Sub</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterStatementTest() VerifyRecommendationsContain(<MethodBody> Dim x |</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Exit | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordTest() VerifyRecommendationsMissing(<MethodBody> With Continue | Loop</MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterContinueKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Continue | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitKeywordOutsideLoopTest() VerifyRecommendationsMissing(<MethodBody> Exit | </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithNotAfterExitInsideLambdaInsideWithBlockTest() VerifyRecommendationsMissing(<MethodBody> While Dim x = Sub() Exit | End Sub Loop </MethodBody>, "With") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterExitInsideWhileLoopInsideLambdaTest() VerifyRecommendationsMissing(<MethodBody> Dim x = Sub() With x Exit | Loop End Sub </MethodBody>, "With") End Sub End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Analyzers/Core/Analyzers/MakeFieldReadonly/MakeFieldReadonlyDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, 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.Concurrent; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MakeFieldReadonly { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] internal sealed class MakeFieldReadonlyDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public MakeFieldReadonlyDiagnosticAnalyzer() : base( IDEDiagnosticIds.MakeFieldReadonlyDiagnosticId, EnforceOnBuildValues.MakeFieldReadonly, CodeStyleOptions2.PreferReadonly, new LocalizableResourceString(nameof(AnalyzersResources.Add_readonly_modifier), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Make_field_readonly), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; // We need to analyze generated code to get callbacks for read/writes to non-generated members in generated code. protected override bool ReceiveAnalysisCallbacksForGeneratedCode => true; protected override void InitializeWorker(AnalysisContext context) { context.RegisterCompilationStartAction(compilationStartContext => { // State map for fields: // 'isCandidate' : Indicates whether the field is a candidate to be made readonly based on it's options. // 'written' : Indicates if there are any writes to the field outside the constructor and field initializer. var fieldStateMap = new ConcurrentDictionary<IFieldSymbol, (bool isCandidate, bool written)>(); var threadStaticAttribute = compilationStartContext.Compilation.ThreadStaticAttributeType(); // We register following actions in the compilation: // 1. A symbol action for field symbols to ensure the field state is initialized for every field in // the compilation. // 2. An operation action for field references to detect if a candidate field is written outside // constructor and field initializer, and update field state accordingly. // 3. A symbol start/end action for named types to report diagnostics for candidate fields that were // not written outside constructor and field initializer. compilationStartContext.RegisterSymbolAction(AnalyzeFieldSymbol, SymbolKind.Field); compilationStartContext.RegisterSymbolStartAction(symbolStartContext => { symbolStartContext.RegisterOperationAction(AnalyzeOperation, OperationKind.FieldReference); symbolStartContext.RegisterSymbolEndAction(OnSymbolEnd); }, SymbolKind.NamedType); return; // Local functions. void AnalyzeFieldSymbol(SymbolAnalysisContext symbolContext) { _ = TryGetOrInitializeFieldState((IFieldSymbol)symbolContext.Symbol, symbolContext.Options, symbolContext.CancellationToken); } void AnalyzeOperation(OperationAnalysisContext operationContext) { var fieldReference = (IFieldReferenceOperation)operationContext.Operation; var (isCandidate, written) = TryGetOrInitializeFieldState(fieldReference.Field, operationContext.Options, operationContext.CancellationToken); // Ignore fields that are not candidates or have already been written outside the constructor/field initializer. if (!isCandidate || written) { return; } // Check if this is a field write outside constructor and field initializer, and update field state accordingly. if (IsFieldWrite(fieldReference, operationContext.ContainingSymbol)) { UpdateFieldStateOnWrite(fieldReference.Field); } } void OnSymbolEnd(SymbolAnalysisContext symbolEndContext) { // Report diagnostics for candidate fields that are not written outside constructor and field initializer. var members = ((INamedTypeSymbol)symbolEndContext.Symbol).GetMembers(); foreach (var member in members) { if (member is IFieldSymbol field && fieldStateMap.TryRemove(field, out var value)) { var (isCandidate, written) = value; if (isCandidate && !written) { var option = GetCodeStyleOption(field, symbolEndContext.Options, symbolEndContext.CancellationToken); var diagnostic = DiagnosticHelper.Create( Descriptor, field.Locations[0], option.Notification.Severity, additionalLocations: null, properties: null); symbolEndContext.ReportDiagnostic(diagnostic); } } } } static bool IsCandidateField(IFieldSymbol symbol, INamedTypeSymbol threadStaticAttribute) => symbol.DeclaredAccessibility == Accessibility.Private && !symbol.IsReadOnly && !symbol.IsConst && !symbol.IsImplicitlyDeclared && symbol.Locations.Length == 1 && symbol.Type.IsMutableValueType() == false && !symbol.IsFixedSizeBuffer && !symbol.GetAttributes().Any( static (a, threadStaticAttribute) => SymbolEqualityComparer.Default.Equals(a.AttributeClass, threadStaticAttribute), threadStaticAttribute); // Method to update the field state for a candidate field written outside constructor and field initializer. void UpdateFieldStateOnWrite(IFieldSymbol field) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); Debug.Assert(fieldStateMap.ContainsKey(field)); fieldStateMap[field] = (isCandidate: true, written: true); } // Method to get or initialize the field state. (bool isCandidate, bool written) TryGetOrInitializeFieldState(IFieldSymbol fieldSymbol, AnalyzerOptions options, CancellationToken cancellationToken) { if (!IsCandidateField(fieldSymbol, threadStaticAttribute)) { return default; } if (fieldStateMap.TryGetValue(fieldSymbol, out var result)) { return result; } result = ComputeInitialFieldState(fieldSymbol, options, threadStaticAttribute, cancellationToken); return fieldStateMap.GetOrAdd(fieldSymbol, result); } // Method to compute the initial field state. static (bool isCandidate, bool written) ComputeInitialFieldState(IFieldSymbol field, AnalyzerOptions options, INamedTypeSymbol threadStaticAttribute, CancellationToken cancellationToken) { Debug.Assert(IsCandidateField(field, threadStaticAttribute)); var option = GetCodeStyleOption(field, options, cancellationToken); if (option == null || !option.Value) { return default; } return (isCandidate: true, written: false); } }); } private static bool IsFieldWrite(IFieldReferenceOperation fieldReference, ISymbol owningSymbol) { // Check if the underlying member is being written or a writable reference to the member is taken. var valueUsageInfo = fieldReference.GetValueUsageInfo(owningSymbol); if (!valueUsageInfo.IsWrittenTo()) { return false; } // Writes to fields inside constructor are ignored, except for the below cases: // 1. Instance reference of an instance field being written is not the instance being initialized by the constructor. // 2. Field is being written inside a lambda or local function. // Check if we are in the constructor of the containing type of the written field. var isInConstructor = owningSymbol.IsConstructor(); var isInStaticConstructor = owningSymbol.IsStaticConstructor(); var field = fieldReference.Field; if ((isInConstructor || isInStaticConstructor) && field.ContainingType == owningSymbol.ContainingType) { // For instance fields, ensure that the instance reference is being initialized by the constructor. var instanceFieldWrittenInCtor = isInConstructor && fieldReference.Instance?.Kind == OperationKind.InstanceReference && !fieldReference.IsTargetOfObjectMemberInitializer(); // For static fields, ensure that we are in the static constructor. var staticFieldWrittenInStaticCtor = isInStaticConstructor && field.IsStatic; if (instanceFieldWrittenInCtor || staticFieldWrittenInStaticCtor) { // Finally, ensure that the write is not inside a lambda or local function. if (fieldReference.TryGetContainingAnonymousFunctionOrLocalFunction() is null) { // It is safe to ignore this write. return false; } } } return true; } private static CodeStyleOption2<bool> GetCodeStyleOption(IFieldSymbol field, AnalyzerOptions options, CancellationToken cancellationToken) => options.GetOption(CodeStyleOptions2.PreferReadonly, field.Language, field.Locations[0].SourceTree, cancellationToken); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Lowering/LocalRewriter/LocalRewriter_ConditionalOperator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// If the condition has a constant value, then just use the selected branch. /// e.g. "true ? x : y" becomes "x". /// </summary> public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { // just a fact, not a requirement (VisitExpression would have rewritten otherwise) Debug.Assert(node.ConstantValue == null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitExpression(node.Consequence); var rewrittenAlternative = VisitExpression(node.Alternative); if (rewrittenCondition.ConstantValue == null) { return node.Update(node.IsRef, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type); } return RewriteConditionalOperator( node.Syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.ConstantValueOpt, node.Type, node.IsRef); } private static BoundExpression RewriteConditionalOperator( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundExpression rewrittenConsequence, BoundExpression rewrittenAlternative, ConstantValue? constantValueOpt, TypeSymbol rewrittenType, bool isRef) { ConstantValue? conditionConstantValue = rewrittenCondition.ConstantValue; if (conditionConstantValue == ConstantValue.True) { return rewrittenConsequence; } else if (conditionConstantValue == ConstantValue.False) { return rewrittenAlternative; } else { return new BoundConditionalOperator( syntax, isRef, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, constantValueOpt, rewrittenType, wasTargetTyped: false, rewrittenType); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { /// <summary> /// If the condition has a constant value, then just use the selected branch. /// e.g. "true ? x : y" becomes "x". /// </summary> public override BoundNode VisitConditionalOperator(BoundConditionalOperator node) { // just a fact, not a requirement (VisitExpression would have rewritten otherwise) Debug.Assert(node.ConstantValue == null); var rewrittenCondition = VisitExpression(node.Condition); var rewrittenConsequence = VisitExpression(node.Consequence); var rewrittenAlternative = VisitExpression(node.Alternative); if (rewrittenCondition.ConstantValue == null) { return node.Update(node.IsRef, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.ConstantValueOpt, node.NaturalTypeOpt, node.WasTargetTyped, node.Type); } return RewriteConditionalOperator( node.Syntax, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, node.ConstantValueOpt, node.Type, node.IsRef); } private static BoundExpression RewriteConditionalOperator( SyntaxNode syntax, BoundExpression rewrittenCondition, BoundExpression rewrittenConsequence, BoundExpression rewrittenAlternative, ConstantValue? constantValueOpt, TypeSymbol rewrittenType, bool isRef) { ConstantValue? conditionConstantValue = rewrittenCondition.ConstantValue; if (conditionConstantValue == ConstantValue.True) { return rewrittenConsequence; } else if (conditionConstantValue == ConstantValue.False) { return rewrittenAlternative; } else { return new BoundConditionalOperator( syntax, isRef, rewrittenCondition, rewrittenConsequence, rewrittenAlternative, constantValueOpt, rewrittenType, wasTargetTyped: false, rewrittenType); } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Utilities/UsingsAndExternAliasesOrganizer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal static partial class UsingsAndExternAliasesOrganizer { private static readonly SyntaxTrivia s_newLine = SyntaxFactory.CarriageReturnLineFeed; public static void Organize( SyntaxList<ExternAliasDirectiveSyntax> externAliasList, SyntaxList<UsingDirectiveSyntax> usingList, bool placeSystemNamespaceFirst, bool separateGroups, out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList, out SyntaxList<UsingDirectiveSyntax> organizedUsingList) { OrganizeWorker( externAliasList, usingList, placeSystemNamespaceFirst, out organizedExternAliasList, out organizedUsingList); if (separateGroups) { if (organizedExternAliasList.Count > 0 && organizedUsingList.Count > 0) { var firstUsing = organizedUsingList[0]; if (!firstUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine())) { var newFirstUsing = firstUsing.WithPrependedLeadingTrivia(s_newLine); organizedUsingList = organizedUsingList.Replace(firstUsing, newFirstUsing); } } for (var i = 1; i < organizedUsingList.Count; i++) { var lastUsing = organizedUsingList[i - 1]; var currentUsing = organizedUsingList[i]; if (NeedsGrouping(lastUsing, currentUsing) && !currentUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine())) { var newCurrentUsing = currentUsing.WithPrependedLeadingTrivia(s_newLine); organizedUsingList = organizedUsingList.Replace(currentUsing, newCurrentUsing); } } } } public static bool NeedsGrouping( UsingDirectiveSyntax using1, UsingDirectiveSyntax using2) { var directive1IsUsingStatic = using1.StaticKeyword.IsKind(SyntaxKind.StaticKeyword); var directive2IsUsingStatic = using2.StaticKeyword.IsKind(SyntaxKind.StaticKeyword); var directive1IsAlias = using1.Alias != null; var directive2IsAlias = using2.Alias != null; var directive1IsNamespace = !directive1IsUsingStatic && !directive1IsAlias; var directive2IsNamespace = !directive2IsUsingStatic && !directive2IsAlias; if (directive1IsAlias && directive2IsAlias) { return false; } if (directive1IsUsingStatic && directive2IsUsingStatic) { return false; } if (directive1IsNamespace && directive2IsNamespace) { // Both normal usings. Place them in groups if their first namespace // component differs. var name1 = using1.Name.GetFirstToken().ValueText; var name2 = using2.Name.GetFirstToken().ValueText; return name1 != name2; } // They have different types, definitely put them into new groups. return true; } private static void OrganizeWorker( SyntaxList<ExternAliasDirectiveSyntax> externAliasList, SyntaxList<UsingDirectiveSyntax> usingList, bool placeSystemNamespaceFirst, out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList, out SyntaxList<UsingDirectiveSyntax> organizedUsingList) { if (externAliasList.Count > 0 || usingList.Count > 0) { // Merge the list of usings and externs into one list. // order them in the order that they were originally in the // file. var initialList = usingList.Cast<SyntaxNode>() .Concat(externAliasList) .OrderBy(n => n.SpanStart).ToList(); if (!initialList.SpansPreprocessorDirective()) { // If there is a banner comment that precedes the nodes, // then remove it and store it for later. initialList[0] = initialList[0].GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var leadingTrivia); var comparer = placeSystemNamespaceFirst ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance : UsingsAndExternAliasesDirectiveComparer.NormalInstance; var finalList = initialList.OrderBy(comparer).ToList(); // Check if sorting the list actually changed anything. If not, then we don't // need to make any changes to the file. if (!finalList.SequenceEqual(initialList)) { // Make sure newlines are correct between nodes. EnsureNewLines(finalList); // Reattach the banner. finalList[0] = finalList[0].WithPrependedLeadingTrivia(leadingTrivia); // Now split out the externs and usings back into two separate lists. organizedExternAliasList = finalList.Where(t => t is ExternAliasDirectiveSyntax) .Cast<ExternAliasDirectiveSyntax>() .ToSyntaxList(); organizedUsingList = finalList.Where(t => t is UsingDirectiveSyntax) .Cast<UsingDirectiveSyntax>() .ToSyntaxList(); return; } } } organizedExternAliasList = externAliasList; organizedUsingList = usingList; } private static void EnsureNewLines(IList<SyntaxNode> list) { // First, make sure that every node (except the last one) ends with // a newline. for (var i = 0; i < list.Count - 1; i++) { var node = list[i]; var trailingTrivia = node.GetTrailingTrivia(); if (!trailingTrivia.Any() || trailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia) { list[i] = node.WithTrailingTrivia(trailingTrivia.Concat(s_newLine)); } } // Now, make sure that every node (except the first one) does *not* // start with newlines. for (var i = 1; i < list.Count; i++) { var node = list[i]; list[i] = TrimLeadingNewLines(node); } list[0] = TrimLeadingNewLines(list[0]); } private static SyntaxNode TrimLeadingNewLines(SyntaxNode node) => node.WithLeadingTrivia(node.GetLeadingTrivia().SkipWhile(t => t.Kind() == SyntaxKind.EndOfLineTrivia)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal static partial class UsingsAndExternAliasesOrganizer { private static readonly SyntaxTrivia s_newLine = SyntaxFactory.CarriageReturnLineFeed; public static void Organize( SyntaxList<ExternAliasDirectiveSyntax> externAliasList, SyntaxList<UsingDirectiveSyntax> usingList, bool placeSystemNamespaceFirst, bool separateGroups, out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList, out SyntaxList<UsingDirectiveSyntax> organizedUsingList) { OrganizeWorker( externAliasList, usingList, placeSystemNamespaceFirst, out organizedExternAliasList, out organizedUsingList); if (separateGroups) { if (organizedExternAliasList.Count > 0 && organizedUsingList.Count > 0) { var firstUsing = organizedUsingList[0]; if (!firstUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine())) { var newFirstUsing = firstUsing.WithPrependedLeadingTrivia(s_newLine); organizedUsingList = organizedUsingList.Replace(firstUsing, newFirstUsing); } } for (var i = 1; i < organizedUsingList.Count; i++) { var lastUsing = organizedUsingList[i - 1]; var currentUsing = organizedUsingList[i]; if (NeedsGrouping(lastUsing, currentUsing) && !currentUsing.GetLeadingTrivia().Any(t => t.IsEndOfLine())) { var newCurrentUsing = currentUsing.WithPrependedLeadingTrivia(s_newLine); organizedUsingList = organizedUsingList.Replace(currentUsing, newCurrentUsing); } } } } public static bool NeedsGrouping( UsingDirectiveSyntax using1, UsingDirectiveSyntax using2) { var directive1IsUsingStatic = using1.StaticKeyword.IsKind(SyntaxKind.StaticKeyword); var directive2IsUsingStatic = using2.StaticKeyword.IsKind(SyntaxKind.StaticKeyword); var directive1IsAlias = using1.Alias != null; var directive2IsAlias = using2.Alias != null; var directive1IsNamespace = !directive1IsUsingStatic && !directive1IsAlias; var directive2IsNamespace = !directive2IsUsingStatic && !directive2IsAlias; if (directive1IsAlias && directive2IsAlias) { return false; } if (directive1IsUsingStatic && directive2IsUsingStatic) { return false; } if (directive1IsNamespace && directive2IsNamespace) { // Both normal usings. Place them in groups if their first namespace // component differs. var name1 = using1.Name.GetFirstToken().ValueText; var name2 = using2.Name.GetFirstToken().ValueText; return name1 != name2; } // They have different types, definitely put them into new groups. return true; } private static void OrganizeWorker( SyntaxList<ExternAliasDirectiveSyntax> externAliasList, SyntaxList<UsingDirectiveSyntax> usingList, bool placeSystemNamespaceFirst, out SyntaxList<ExternAliasDirectiveSyntax> organizedExternAliasList, out SyntaxList<UsingDirectiveSyntax> organizedUsingList) { if (externAliasList.Count > 0 || usingList.Count > 0) { // Merge the list of usings and externs into one list. // order them in the order that they were originally in the // file. var initialList = usingList.Cast<SyntaxNode>() .Concat(externAliasList) .OrderBy(n => n.SpanStart).ToList(); if (!initialList.SpansPreprocessorDirective()) { // If there is a banner comment that precedes the nodes, // then remove it and store it for later. initialList[0] = initialList[0].GetNodeWithoutLeadingBannerAndPreprocessorDirectives(out var leadingTrivia); var comparer = placeSystemNamespaceFirst ? UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance : UsingsAndExternAliasesDirectiveComparer.NormalInstance; var finalList = initialList.OrderBy(comparer).ToList(); // Check if sorting the list actually changed anything. If not, then we don't // need to make any changes to the file. if (!finalList.SequenceEqual(initialList)) { // Make sure newlines are correct between nodes. EnsureNewLines(finalList); // Reattach the banner. finalList[0] = finalList[0].WithPrependedLeadingTrivia(leadingTrivia); // Now split out the externs and usings back into two separate lists. organizedExternAliasList = finalList.Where(t => t is ExternAliasDirectiveSyntax) .Cast<ExternAliasDirectiveSyntax>() .ToSyntaxList(); organizedUsingList = finalList.Where(t => t is UsingDirectiveSyntax) .Cast<UsingDirectiveSyntax>() .ToSyntaxList(); return; } } } organizedExternAliasList = externAliasList; organizedUsingList = usingList; } private static void EnsureNewLines(IList<SyntaxNode> list) { // First, make sure that every node (except the last one) ends with // a newline. for (var i = 0; i < list.Count - 1; i++) { var node = list[i]; var trailingTrivia = node.GetTrailingTrivia(); if (!trailingTrivia.Any() || trailingTrivia.Last().Kind() != SyntaxKind.EndOfLineTrivia) { list[i] = node.WithTrailingTrivia(trailingTrivia.Concat(s_newLine)); } } // Now, make sure that every node (except the first one) does *not* // start with newlines. for (var i = 1; i < list.Count; i++) { var node = list[i]; list[i] = TrimLeadingNewLines(node); } list[0] = TrimLeadingNewLines(list[0]); } private static SyntaxNode TrimLeadingNewLines(SyntaxNode node) => node.WithLeadingTrivia(node.GetLeadingTrivia().SkipWhile(t => t.Kind() == SyntaxKind.EndOfLineTrivia)); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/EditorConfigSettings/Analyzers/ViewModel/AnalyzerSettingsViewModel.SettingsSnapshotFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<AnalyzerSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<AnalyzerSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel { internal partial class AnalyzerSettingsViewModel : SettingsViewModelBase< AnalyzerSetting, AnalyzerSettingsViewModel.SettingsSnapshotFactory, AnalyzerSettingsViewModel.SettingsEntriesSnapshot> { internal sealed class SettingsSnapshotFactory : SettingsSnapshotFactoryBase<AnalyzerSetting, SettingsEntriesSnapshot> { public SettingsSnapshotFactory(ISettingsProvider<AnalyzerSetting> data) : base(data) { } protected override SettingsEntriesSnapshot CreateSnapshot(ImmutableArray<AnalyzerSetting> data, int currentVersionNumber) => new(data, currentVersionNumber); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Utilities/CompilerUtilities/ImmutableHashMap.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Contract = System.Diagnostics.Contracts.Contract; namespace Roslyn.Collections.Immutable { /// <summary> /// An immutable unordered hash map implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue> where TKey : notnull { private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new(); /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly Bucket? _root; /// <summary> /// The comparer used to sort keys in this map. /// </summary> private readonly IEqualityComparer<TKey> _keyComparer; /// <summary> /// The comparer used to detect equivalent values in this map. /// </summary> private readonly IEqualityComparer<TValue> _valueComparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer) : this(comparer, valueComparer) { RoslynDebug.AssertNotNull(comparer); RoslynDebug.AssertNotNull(valueComparer); _root = root; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null) { _keyComparer = comparer ?? EqualityComparer<TKey>.Default; _valueComparer = valueComparer ?? EqualityComparer<TValue>.Default; } /// <summary> /// Gets an empty map with default equality comparers. /// </summary> public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton; /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public ImmutableHashMap<TKey, TValue> Clear() => this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer); #region Public methods /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false)); } } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true)); } } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); if (_root != null) { return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer)); } return this; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var map = _root; if (map != null) { foreach (var key in keys) { map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer); if (map == null) { break; } } } return this.Wrap(map); } /// <summary> /// Returns a hash map that uses the specified key and value comparers and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (_keyComparer == keyComparer) { if (_valueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer); } } else { var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer); set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true); return set; } } /// <summary> /// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) => this.WithComparers(keyComparer, _valueComparer); /// <summary> /// Determines whether the ImmutableSortedMap&lt;TKey,TValue&gt; /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the ImmutableSortedMap&lt;TKey,TValue&gt;. /// The value can be null for reference types. /// </param> /// <returns> /// true if the ImmutableSortedMap&lt;TKey,TValue&gt; contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) => this.Values.Contains(value, _valueComparer); #endregion #region IImmutableDictionary<TKey, TValue> Members /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _root != null ? _root.Count : 0; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb.Key; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { #pragma warning disable 618 get { return this.GetValueBuckets().Select(vb => vb.Value); } #pragma warning restore 618 } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { if (this.TryGetValue(key, out var value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); return vb != null; } return false; } /// <summary> /// Determines whether this map contains the specified key-value pair. /// </summary> /// <param name="keyValuePair">The key value pair.</param> /// <returns> /// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> keyValuePair) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer); return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value); } return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> #pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); if (vb != null) { value = vb.Value; return true; } } value = default; return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer); if (vb != null) { actualKey = vb.Key; return true; } } actualKey = equalKey; return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator(); #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { var builder = new StringBuilder("ImmutableHashMap["); var needComma = false; foreach (var kv in this) { builder.Append(kv.Key); builder.Append(":"); builder.Append(kv.Value); if (needComma) { builder.Append(","); } needComma = true; } builder.Append("]"); return builder.ToString(); } /// <summary> /// Exchanges a key for the actual key instance found in this map. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="existingKey">Receives the equal key found in the map.</param> /// <returns>A value indicating whether an equal and existing key was found in the map.</returns> internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey) { var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null; if (vb != null) { existingKey = vb.Key; return true; } else { existingKey = default; return false; } } /// <summary> /// Attempts to discover an <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other) { other = sequence as ImmutableHashMap<TKey, TValue>; if (other != null) { return true; } return false; } private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root) { if (root == null) { return this.Clear(); } if (_root != root) { return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param> [Pure] private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap) { RoslynDebug.AssertNotNull(pairs); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableHashMap<TKey, TValue> // then there is no value in reconstructing it. if (TryCastToImmutableMap(pairs, out var other)) { return other.WithComparers(_keyComparer, _valueComparer); } } var map = this; foreach (var pair in pairs) { map = overwriteOnCollision ? map.SetItem(pair.Key, pair.Value) : map.Add(pair.Key, pair.Value); } return map; } private IEnumerable<ValueBucket> GetValueBuckets() { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } private abstract class Bucket { internal abstract int Count { get; } internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue); internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract IEnumerable<Bucket> GetAll(); } private abstract class ValueOrListBucket : Bucket { /// <summary> /// The hash for this bucket. /// </summary> internal readonly int Hash; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueOrListBucket"/> class. /// </summary> /// <param name="hash">The hash.</param> protected ValueOrListBucket(int hash) => this.Hash = hash; } private sealed class ValueBucket : ValueOrListBucket { internal readonly TKey Key; internal readonly TValue Value; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueBucket"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="hashcode">The hashcode.</param> internal ValueBucket(TKey key, TValue value, int hashcode) : base(hashcode) { this.Key = key; this.Value = value; } internal override int Count => 1; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { if (comparer.Equals(this.Key, bucket.Key)) { // Overwrite of same key. If the value is the same as well, don't switch out the bucket. if (valueComparer.Equals(this.Value, bucket.Value)) { return this; } else { if (overwriteExistingValue) { return bucket; } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { // two of the same hash will never be happy in a hash bucket return new ListBucket(new ValueBucket[] { this, bucket }); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return null; } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return this; } return null; } internal override IEnumerable<Bucket> GetAll() => SpecializedCollections.SingletonEnumerable(this); } private sealed class ListBucket : ValueOrListBucket { private readonly ValueBucket[] _buckets; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ListBucket"/> class. /// </summary> /// <param name="buckets">The buckets.</param> internal ListBucket(ValueBucket[] buckets) : base(buckets[0].Hash) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length >= 2); _buckets = buckets; } internal override int Count => _buckets.Length; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { var pos = this.Find(bucket.Key, comparer); if (pos >= 0) { // If the value hasn't changed for this key, return the original bucket. if (valueComparer.Equals(bucket.Value, _buckets[pos].Value)) { return this; } else { if (overwriteExistingValue) { return new ListBucket(_buckets.ReplaceAt(pos, bucket)); } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket)); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return pos == 0 ? _buckets[1] : _buckets[0]; } else { return new ListBucket(_buckets.RemoveAt(pos)); } } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { return _buckets[pos]; } } return null; } private int Find(TKey key, IEqualityComparer<TKey> comparer) { for (var i = 0; i < _buckets.Length; i++) { if (comparer.Equals(key, _buckets[i].Key)) { return i; } } return -1; } internal override IEnumerable<Bucket> GetAll() => _buckets; } private sealed class HashBucket : Bucket { private readonly int _hashRoll; private readonly uint _used; private readonly Bucket[] _buckets; private readonly int _count; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="hashRoll">The hash roll.</param> /// <param name="used">The used.</param> /// <param name="buckets">The buckets.</param> /// <param name="count">The count.</param> private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length == CountBits(used)); _hashRoll = hashRoll & 31; _used = used; _buckets = buckets; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="suggestedHashRoll">The suggested hash roll.</param> /// <param name="bucket1">The bucket1.</param> /// <param name="bucket2">The bucket2.</param> internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2) { RoslynDebug.AssertNotNull(bucket1); RoslynDebug.AssertNotNull(bucket2); Debug.Assert(bucket1.Hash != bucket2.Hash); // find next hashRoll that causes these two to be slotted in different buckets var h1 = bucket1.Hash; var h2 = bucket2.Hash; int s1; int s2; for (var i = 0; i < 32; i++) { _hashRoll = (suggestedHashRoll + i) & 31; s1 = this.ComputeLogicalSlot(h1); s2 = this.ComputeLogicalSlot(h2); if (s1 != s2) { _count = 2; _used = (1u << s1) | (1u << s2); _buckets = new Bucket[2]; _buckets[this.ComputePhysicalSlot(s1)] = bucket1; _buckets[this.ComputePhysicalSlot(s2)] = bucket2; return; } } throw new InvalidOperationException(); } internal override int Count => _count; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { var logicalSlot = ComputeLogicalSlot(bucket.Hash); if (IsInUse(logicalSlot)) { // if this slot is in use, then add the new item to the one in this slot var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; // suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot // note: we ignore passed in suggestion, and base new suggestion off current hash roll. var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue); if (added != existing) { var newBuckets = _buckets.ReplaceAt(physicalSlot, added); return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count); } else { return this; } } else { var physicalSlot = ComputePhysicalSlot(logicalSlot); var newBuckets = _buckets.InsertAt(physicalSlot, bucket); var newUsed = InsertBit(logicalSlot, _used); return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; var result = existing.Remove(hash, key, comparer); if (result == null) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return physicalSlot == 0 ? _buckets[1] : _buckets[0]; } else { return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count); } } else if (_buckets[physicalSlot] != result) { return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count); } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); return _buckets[physicalSlot].Get(hash, key, comparer); } return null; } internal override IEnumerable<Bucket> GetAll() => _buckets; private bool IsInUse(int logicalSlot) => ((1 << logicalSlot) & _used) != 0; private int ComputeLogicalSlot(int hc) { var uc = unchecked((uint)hc); var rotated = RotateRight(uc, _hashRoll); return unchecked((int)(rotated & 31)); } [Pure] private static uint RotateRight(uint v, int n) { Debug.Assert(n >= 0 && n < 32); if (n == 0) { return v; } return v >> n | (v << (32 - n)); } private int ComputePhysicalSlot(int logicalSlot) { Debug.Assert(logicalSlot >= 0 && logicalSlot < 32); Contract.Ensures(Contract.Result<int>() >= 0); if (_buckets.Length == 32) { return logicalSlot; } if (logicalSlot == 0) { return 0; } var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot # return CountBits(_used & mask); } [Pure] private static int CountBits(uint v) { unchecked { v -= ((v >> 1) & 0x55555555u); v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } } [Pure] private static uint InsertBit(int position, uint bits) { Debug.Assert(0 == (bits & (1u << position))); return bits | (1u << position); } [Pure] private static uint RemoveBit(int position, uint bits) { Debug.Assert(0 != (bits & (1u << position))); return bits & ~(1u << position); } } #region IImmutableDictionary<TKey,TValue> Members IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() => this.Clear(); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) => this.Add(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) => this.SetItem(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) => this.SetItems(items); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) => this.AddRange(pairs); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) => this.RemoveRange(keys); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => this.Remove(key); #endregion /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> private class DebuggerProxy { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableHashMap<TKey, TValue> _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[]? _contents; /// <summary> /// Initializes a new instance of the <see cref="DebuggerProxy"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public DebuggerProxy(ImmutableHashMap<TKey, TValue> map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(); } return _contents; } } } private static class Requires { [DebuggerStepThrough] public static T NotNullAllowStructs<T>(T value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static T NotNull<T>(T value, string parameterName) where T : class { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static Exception FailRange(string parameterName, string? message = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentOutOfRangeException(parameterName); } throw new ArgumentOutOfRangeException(parameterName, message); } [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string? message = null) { if (!condition) { Requires.FailRange(parameterName, message); } } } private static class Strings { public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using Microsoft.CodeAnalysis; using Roslyn.Utilities; using Contract = System.Diagnostics.Contracts.Contract; namespace Roslyn.Collections.Immutable { /// <summary> /// An immutable unordered hash map implementation. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashMap<,>.DebuggerProxy))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] internal sealed class ImmutableHashMap<TKey, TValue> : IImmutableDictionary<TKey, TValue> where TKey : notnull { private static readonly ImmutableHashMap<TKey, TValue> s_emptySingleton = new(); /// <summary> /// The root node of the tree that stores this map. /// </summary> private readonly Bucket? _root; /// <summary> /// The comparer used to sort keys in this map. /// </summary> private readonly IEqualityComparer<TKey> _keyComparer; /// <summary> /// The comparer used to detect equivalent values in this map. /// </summary> private readonly IEqualityComparer<TValue> _valueComparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="root">The root.</param> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> private ImmutableHashMap(Bucket? root, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer) : this(comparer, valueComparer) { RoslynDebug.AssertNotNull(comparer); RoslynDebug.AssertNotNull(valueComparer); _root = root; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> class. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="valueComparer">The value comparer.</param> internal ImmutableHashMap(IEqualityComparer<TKey>? comparer = null, IEqualityComparer<TValue>? valueComparer = null) { _keyComparer = comparer ?? EqualityComparer<TKey>.Default; _valueComparer = valueComparer ?? EqualityComparer<TValue>.Default; } /// <summary> /// Gets an empty map with default equality comparers. /// </summary> public static ImmutableHashMap<TKey, TValue> Empty => s_emptySingleton; /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public ImmutableHashMap<TKey, TValue> Clear() => this.IsEmpty ? this : Empty.WithComparers(_keyComparer, _valueComparer); #region Public methods /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Add(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, false)); } } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) { Requires.NotNull(pairs, "pairs"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); return this.AddRange(pairs, overwriteOnCollision: false, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> SetItem(TKey key, TValue value) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); Contract.Ensures(!Contract.Result<ImmutableHashMap<TKey, TValue>>().IsEmpty); var vb = new ValueBucket(key, value, _keyComparer.GetHashCode(key)); if (_root == null) { return this.Wrap(vb); } else { return this.Wrap(_root.Add(0, vb, _keyComparer, _valueComparer, true)); } } /// <summary> /// Applies a given set of key=value pairs to an immutable dictionary, replacing any conflicting keys in the resulting dictionary. /// </summary> /// <param name="items">The key=value pairs to set on the map. Any keys that conflict with existing keys will overwrite the previous values.</param> /// <returns>An immutable dictionary.</returns> [Pure] public ImmutableHashMap<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return this.AddRange(items, overwriteOnCollision: true, avoidToHashMap: false); } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> Remove(TKey key) { Requires.NotNullAllowStructs(key, "key"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); if (_root != null) { return this.Wrap(_root.Remove(_keyComparer.GetHashCode(key), key, _keyComparer)); } return this; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> [Pure] public ImmutableHashMap<TKey, TValue> RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, "keys"); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); var map = _root; if (map != null) { foreach (var key in keys) { map = map.Remove(_keyComparer.GetHashCode(key), key, _keyComparer); if (map == null) { break; } } } return this.Wrap(map); } /// <summary> /// Returns a hash map that uses the specified key and value comparers and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <param name="valueComparer">The value comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { if (keyComparer == null) { keyComparer = EqualityComparer<TKey>.Default; } if (valueComparer == null) { valueComparer = EqualityComparer<TValue>.Default; } if (_keyComparer == keyComparer) { if (_valueComparer == valueComparer) { return this; } else { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. return new ImmutableHashMap<TKey, TValue>(_root, _keyComparer, valueComparer); } } else { var set = new ImmutableHashMap<TKey, TValue>(keyComparer, valueComparer); set = set.AddRange(this, overwriteOnCollision: false, avoidToHashMap: true); return set; } } /// <summary> /// Returns a hash map that uses the specified key comparer and current value comparer and has the same contents as this map. /// </summary> /// <param name="keyComparer">The key comparer. A value of <c>null</c> results in using the default equality comparer for the type.</param> /// <returns>The hash map with the new comparers.</returns> /// <remarks> /// In the event that a change in the key equality comparer results in a key collision, an exception is thrown. /// </remarks> [Pure] public ImmutableHashMap<TKey, TValue> WithComparers(IEqualityComparer<TKey> keyComparer) => this.WithComparers(keyComparer, _valueComparer); /// <summary> /// Determines whether the ImmutableSortedMap&lt;TKey,TValue&gt; /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the ImmutableSortedMap&lt;TKey,TValue&gt;. /// The value can be null for reference types. /// </param> /// <returns> /// true if the ImmutableSortedMap&lt;TKey,TValue&gt; contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) => this.Values.Contains(value, _valueComparer); #endregion #region IImmutableDictionary<TKey, TValue> Members /// <summary> /// Gets the number of elements in this collection. /// </summary> public int Count { get { return _root != null ? _root.Count : 0; } } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { return this.Count == 0; } } /// <summary> /// Gets the keys in the map. /// </summary> public IEnumerable<TKey> Keys { get { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb.Key; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } } /// <summary> /// Gets the values in the map. /// </summary> public IEnumerable<TValue> Values { #pragma warning disable 618 get { return this.GetValueBuckets().Select(vb => vb.Value); } #pragma warning restore 618 } /// <summary> /// Gets the <typeparamref name="TValue"/> with the specified key. /// </summary> public TValue this[TKey key] { get { if (this.TryGetValue(key, out var value)) { return value; } throw new KeyNotFoundException(); } } /// <summary> /// Determines whether the specified key contains key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public bool ContainsKey(TKey key) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); return vb != null; } return false; } /// <summary> /// Determines whether this map contains the specified key-value pair. /// </summary> /// <param name="keyValuePair">The key value pair.</param> /// <returns> /// <c>true</c> if this map contains the key-value pair; otherwise, <c>false</c>. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> keyValuePair) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(keyValuePair.Key), keyValuePair.Key, _keyComparer); return vb != null && _valueComparer.Equals(vb.Value, keyValuePair.Value); } return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> #pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) #pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes). { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer); if (vb != null) { value = vb.Value; return true; } } value = default; return false; } /// <summary> /// See the <see cref="IImmutableDictionary&lt;TKey, TValue&gt;"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { if (_root != null) { var vb = _root.Get(_keyComparer.GetHashCode(equalKey), equalKey, _keyComparer); if (vb != null) { actualKey = vb.Key; return true; } } actualKey = equalKey; return false; } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => this.GetValueBuckets().Select(vb => new KeyValuePair<TKey, TValue>(vb.Key, vb.Value)).GetEnumerator(); #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); #endregion /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String" /> that represents this instance. /// </returns> public override string ToString() { var builder = new StringBuilder("ImmutableHashMap["); var needComma = false; foreach (var kv in this) { builder.Append(kv.Key); builder.Append(":"); builder.Append(kv.Value); if (needComma) { builder.Append(","); } needComma = true; } builder.Append("]"); return builder.ToString(); } /// <summary> /// Exchanges a key for the actual key instance found in this map. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="existingKey">Receives the equal key found in the map.</param> /// <returns>A value indicating whether an equal and existing key was found in the map.</returns> internal bool TryExchangeKey(TKey key, [NotNullWhen(true)] out TKey? existingKey) { var vb = _root != null ? _root.Get(_keyComparer.GetHashCode(key), key, _keyComparer) : null; if (vb != null) { existingKey = vb.Key; return true; } else { existingKey = default; return false; } } /// <summary> /// Attempts to discover an <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> instance beneath some enumerable sequence /// if one exists. /// </summary> /// <param name="sequence">The sequence that may have come from an immutable map.</param> /// <param name="other">Receives the concrete <see cref="ImmutableHashMap&lt;TKey, TValue&gt;"/> typed value if one can be found.</param> /// <returns><c>true</c> if the cast was successful; <c>false</c> otherwise.</returns> private static bool TryCastToImmutableMap(IEnumerable<KeyValuePair<TKey, TValue>> sequence, [NotNullWhen(true)] out ImmutableHashMap<TKey, TValue>? other) { other = sequence as ImmutableHashMap<TKey, TValue>; if (other != null) { return true; } return false; } private ImmutableHashMap<TKey, TValue> Wrap(Bucket? root) { if (root == null) { return this.Clear(); } if (_root != root) { return root.Count == 0 ? this.Clear() : new ImmutableHashMap<TKey, TValue>(root, _keyComparer, _valueComparer); } return this; } /// <summary> /// Bulk adds entries to the map. /// </summary> /// <param name="pairs">The entries to add.</param> /// <param name="overwriteOnCollision"><c>true</c> to allow the <paramref name="pairs"/> sequence to include duplicate keys and let the last one win; <c>false</c> to throw on collisions.</param> /// <param name="avoidToHashMap"><c>true</c> when being called from ToHashMap to avoid StackOverflow.</param> [Pure] private ImmutableHashMap<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs, bool overwriteOnCollision, bool avoidToHashMap) { RoslynDebug.AssertNotNull(pairs); Contract.Ensures(Contract.Result<ImmutableHashMap<TKey, TValue>>() != null); // Some optimizations may apply if we're an empty list. if (this.IsEmpty && !avoidToHashMap) { // If the items being added actually come from an ImmutableHashMap<TKey, TValue> // then there is no value in reconstructing it. if (TryCastToImmutableMap(pairs, out var other)) { return other.WithComparers(_keyComparer, _valueComparer); } } var map = this; foreach (var pair in pairs) { map = overwriteOnCollision ? map.SetItem(pair.Key, pair.Value) : map.Add(pair.Key, pair.Value); } return map; } private IEnumerable<ValueBucket> GetValueBuckets() { if (_root == null) { yield break; } var stack = new Stack<IEnumerator<Bucket>>(); stack.Push(_root.GetAll().GetEnumerator()); while (stack.Count > 0) { var en = stack.Peek(); if (en.MoveNext()) { if (en.Current is ValueBucket vb) { yield return vb; } else { stack.Push(en.Current.GetAll().GetEnumerator()); } } else { stack.Pop(); } } } private abstract class Bucket { internal abstract int Count { get; } internal abstract Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue); internal abstract Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer); internal abstract IEnumerable<Bucket> GetAll(); } private abstract class ValueOrListBucket : Bucket { /// <summary> /// The hash for this bucket. /// </summary> internal readonly int Hash; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueOrListBucket"/> class. /// </summary> /// <param name="hash">The hash.</param> protected ValueOrListBucket(int hash) => this.Hash = hash; } private sealed class ValueBucket : ValueOrListBucket { internal readonly TKey Key; internal readonly TValue Value; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ValueBucket"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="hashcode">The hashcode.</param> internal ValueBucket(TKey key, TValue value, int hashcode) : base(hashcode) { this.Key = key; this.Value = value; } internal override int Count => 1; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { if (comparer.Equals(this.Key, bucket.Key)) { // Overwrite of same key. If the value is the same as well, don't switch out the bucket. if (valueComparer.Equals(this.Value, bucket.Value)) { return this; } else { if (overwriteExistingValue) { return bucket; } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { // two of the same hash will never be happy in a hash bucket return new ListBucket(new ValueBucket[] { this, bucket }); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return null; } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash && comparer.Equals(this.Key, key)) { return this; } return null; } internal override IEnumerable<Bucket> GetAll() => SpecializedCollections.SingletonEnumerable(this); } private sealed class ListBucket : ValueOrListBucket { private readonly ValueBucket[] _buckets; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.ListBucket"/> class. /// </summary> /// <param name="buckets">The buckets.</param> internal ListBucket(ValueBucket[] buckets) : base(buckets[0].Hash) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length >= 2); _buckets = buckets; } internal override int Count => _buckets.Length; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> comparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { if (this.Hash == bucket.Hash) { var pos = this.Find(bucket.Key, comparer); if (pos >= 0) { // If the value hasn't changed for this key, return the original bucket. if (valueComparer.Equals(bucket.Value, _buckets[pos].Value)) { return this; } else { if (overwriteExistingValue) { return new ListBucket(_buckets.ReplaceAt(pos, bucket)); } else { throw new ArgumentException(Strings.DuplicateKey); } } } else { return new ListBucket(_buckets.InsertAt(_buckets.Length, bucket)); } } else { return new HashBucket(suggestedHashRoll, this, bucket); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return pos == 0 ? _buckets[1] : _buckets[0]; } else { return new ListBucket(_buckets.RemoveAt(pos)); } } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { if (this.Hash == hash) { var pos = this.Find(key, comparer); if (pos >= 0) { return _buckets[pos]; } } return null; } private int Find(TKey key, IEqualityComparer<TKey> comparer) { for (var i = 0; i < _buckets.Length; i++) { if (comparer.Equals(key, _buckets[i].Key)) { return i; } } return -1; } internal override IEnumerable<Bucket> GetAll() => _buckets; } private sealed class HashBucket : Bucket { private readonly int _hashRoll; private readonly uint _used; private readonly Bucket[] _buckets; private readonly int _count; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="hashRoll">The hash roll.</param> /// <param name="used">The used.</param> /// <param name="buckets">The buckets.</param> /// <param name="count">The count.</param> private HashBucket(int hashRoll, uint used, Bucket[] buckets, int count) { RoslynDebug.AssertNotNull(buckets); Debug.Assert(buckets.Length == CountBits(used)); _hashRoll = hashRoll & 31; _used = used; _buckets = buckets; _count = count; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashMap&lt;TKey, TValue&gt;.HashBucket"/> class. /// </summary> /// <param name="suggestedHashRoll">The suggested hash roll.</param> /// <param name="bucket1">The bucket1.</param> /// <param name="bucket2">The bucket2.</param> internal HashBucket(int suggestedHashRoll, ValueOrListBucket bucket1, ValueOrListBucket bucket2) { RoslynDebug.AssertNotNull(bucket1); RoslynDebug.AssertNotNull(bucket2); Debug.Assert(bucket1.Hash != bucket2.Hash); // find next hashRoll that causes these two to be slotted in different buckets var h1 = bucket1.Hash; var h2 = bucket2.Hash; int s1; int s2; for (var i = 0; i < 32; i++) { _hashRoll = (suggestedHashRoll + i) & 31; s1 = this.ComputeLogicalSlot(h1); s2 = this.ComputeLogicalSlot(h2); if (s1 != s2) { _count = 2; _used = (1u << s1) | (1u << s2); _buckets = new Bucket[2]; _buckets[this.ComputePhysicalSlot(s1)] = bucket1; _buckets[this.ComputePhysicalSlot(s2)] = bucket2; return; } } throw new InvalidOperationException(); } internal override int Count => _count; internal override Bucket Add(int suggestedHashRoll, ValueBucket bucket, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, bool overwriteExistingValue) { var logicalSlot = ComputeLogicalSlot(bucket.Hash); if (IsInUse(logicalSlot)) { // if this slot is in use, then add the new item to the one in this slot var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; // suggest hash roll that will cause any nested hash bucket to use entirely new bits for picking logical slot // note: we ignore passed in suggestion, and base new suggestion off current hash roll. var added = existing.Add(_hashRoll + 5, bucket, keyComparer, valueComparer, overwriteExistingValue); if (added != existing) { var newBuckets = _buckets.ReplaceAt(physicalSlot, added); return new HashBucket(_hashRoll, _used, newBuckets, _count - existing.Count + added.Count); } else { return this; } } else { var physicalSlot = ComputePhysicalSlot(logicalSlot); var newBuckets = _buckets.InsertAt(physicalSlot, bucket); var newUsed = InsertBit(logicalSlot, _used); return new HashBucket(_hashRoll, newUsed, newBuckets, _count + bucket.Count); } } internal override Bucket? Remove(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); var existing = _buckets[physicalSlot]; var result = existing.Remove(hash, key, comparer); if (result == null) { if (_buckets.Length == 1) { return null; } else if (_buckets.Length == 2) { return physicalSlot == 0 ? _buckets[1] : _buckets[0]; } else { return new HashBucket(_hashRoll, RemoveBit(logicalSlot, _used), _buckets.RemoveAt(physicalSlot), _count - existing.Count); } } else if (_buckets[physicalSlot] != result) { return new HashBucket(_hashRoll, _used, _buckets.ReplaceAt(physicalSlot, result), _count - existing.Count + result.Count); } } return this; } internal override ValueBucket? Get(int hash, TKey key, IEqualityComparer<TKey> comparer) { var logicalSlot = ComputeLogicalSlot(hash); if (IsInUse(logicalSlot)) { var physicalSlot = ComputePhysicalSlot(logicalSlot); return _buckets[physicalSlot].Get(hash, key, comparer); } return null; } internal override IEnumerable<Bucket> GetAll() => _buckets; private bool IsInUse(int logicalSlot) => ((1 << logicalSlot) & _used) != 0; private int ComputeLogicalSlot(int hc) { var uc = unchecked((uint)hc); var rotated = RotateRight(uc, _hashRoll); return unchecked((int)(rotated & 31)); } [Pure] private static uint RotateRight(uint v, int n) { Debug.Assert(n >= 0 && n < 32); if (n == 0) { return v; } return v >> n | (v << (32 - n)); } private int ComputePhysicalSlot(int logicalSlot) { Debug.Assert(logicalSlot >= 0 && logicalSlot < 32); Contract.Ensures(Contract.Result<int>() >= 0); if (_buckets.Length == 32) { return logicalSlot; } if (logicalSlot == 0) { return 0; } var mask = uint.MaxValue >> (32 - logicalSlot); // only count the bits up to the logical slot # return CountBits(_used & mask); } [Pure] private static int CountBits(uint v) { unchecked { v -= ((v >> 1) & 0x55555555u); v = (v & 0x33333333u) + ((v >> 2) & 0x33333333u); return (int)((v + (v >> 4) & 0xF0F0F0Fu) * 0x1010101u) >> 24; } } [Pure] private static uint InsertBit(int position, uint bits) { Debug.Assert(0 == (bits & (1u << position))); return bits | (1u << position); } [Pure] private static uint RemoveBit(int position, uint bits) { Debug.Assert(0 != (bits & (1u << position))); return bits & ~(1u << position); } } #region IImmutableDictionary<TKey,TValue> Members IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Clear() => this.Clear(); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Add(TKey key, TValue value) => this.Add(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItem(TKey key, TValue value) => this.SetItem(key, value); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items) => this.SetItems(items); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs) => this.AddRange(pairs); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.RemoveRange(IEnumerable<TKey> keys) => this.RemoveRange(keys); IImmutableDictionary<TKey, TValue> IImmutableDictionary<TKey, TValue>.Remove(TKey key) => this.Remove(key); #endregion /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> private class DebuggerProxy { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableHashMap<TKey, TValue> _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[]? _contents; /// <summary> /// Initializes a new instance of the <see cref="DebuggerProxy"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public DebuggerProxy(ImmutableHashMap<TKey, TValue> map) { Requires.NotNull(map, "map"); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(); } return _contents; } } } private static class Requires { [DebuggerStepThrough] public static T NotNullAllowStructs<T>(T value, string parameterName) { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static T NotNull<T>(T value, string parameterName) where T : class { if (value == null) { throw new ArgumentNullException(parameterName); } return value; } [DebuggerStepThrough] public static Exception FailRange(string parameterName, string? message = null) { if (string.IsNullOrEmpty(message)) { throw new ArgumentOutOfRangeException(parameterName); } throw new ArgumentOutOfRangeException(parameterName, message); } [DebuggerStepThrough] public static void Range(bool condition, string parameterName, string? message = null) { if (!condition) { Requires.FailRange(parameterName, message); } } } private static class Strings { public static string DuplicateKey => CompilerExtensionsResources.An_element_with_the_same_key_but_a_different_value_already_exists; } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/LanguageService/VisualBasicPackage.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop Imports Task = System.Threading.Tasks.Task Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic ' The option page configuration is duplicated in PackageRegistration.pkgdef. ' ' VB option pages tree ' Basic ' General (from editor) ' Scroll Bars (from editor) ' Tabs (from editor) ' Advanced ' Code Style (category) ' General <ProvideLanguageEditorOptionPage(GetType(AdvancedOptionPage), "Basic", Nothing, "Advanced", "#102", 10160)> <ProvideLanguageEditorToolsOptionCategory("Basic", "Code Style", "#109")> <ProvideLanguageEditorOptionPage(GetType(CodeStylePage), "Basic", "Code Style", "General", "#111", 10161)> <ProvideLanguageEditorOptionPage(GetType(NamingStylesOptionPage), "Basic", "Code Style", "Naming", "#110", 10162)> <ProvideLanguageEditorOptionPage(GetType(IntelliSenseOptionPage), "Basic", Nothing, "IntelliSense", "#112", 312)> <Guid(Guids.VisualBasicPackageIdString)> Friend NotInheritable Class VisualBasicPackage Inherits AbstractPackage(Of VisualBasicPackage, VisualBasicLanguageService) Implements IVbCompilerService Implements IVsUserSettingsQuery ' The property page for WinForms project has a special interface that it uses to get ' entry points that are Forms: IVbEntryPointProvider. The semantics for this ' interface are the same as VisualBasicProject::GetFormEntryPoints, but callers get ' the VB Package and cast it to IVbEntryPointProvider. The property page is managed ' and we've redefined the interface, so we have to register a COM aggregate of the ' VB package. This is the same pattern we use for the LanguageService and Razor. Private ReadOnly _comAggregate As Object Private _libraryManager As ObjectBrowserLibraryManager Private _libraryManagerCookie As UInteger Public Sub New() MyBase.New() _comAggregate = Interop.ComAggregate.CreateAggregatedObject(Me) End Sub Protected Overrides Async Function InitializeAsync(cancellationToken As CancellationToken, progress As IProgress(Of ServiceProgressData)) As Task Try Await MyBase.InitializeAsync(cancellationToken, progress).ConfigureAwait(True) Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) RegisterLanguageService(GetType(IVbCompilerService), Function() Task.FromResult(_comAggregate)) RegisterService(Of IVbTempPECompilerFactory)( Async Function(ct) Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(ct) Return New TempPECompilerFactory(workspace) End Function) Catch ex As Exception When FatalError.ReportAndPropagateUnlessCanceled(ex) Throw ExceptionUtilities.Unreachable End Try End Function Protected Overrides Async Function RegisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Dim workspace As VisualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then Me._libraryManager = New ObjectBrowserLibraryManager(Me, ComponentModel, workspace) If ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(Me._libraryManager, Me._libraryManagerCookie)) Then Me._libraryManagerCookie = 0 End If End If End Function Protected Overrides Async Function UnregisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) If _libraryManagerCookie <> 0 Then Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then objectManager.UnregisterLibrary(Me._libraryManagerCookie) Me._libraryManagerCookie = 0 End If Me._libraryManager.Dispose() Me._libraryManager = Nothing End If End Function Public Function NeedExport(pageID As String, <Out> ByRef needExportParam As Integer) As Integer Implements IVsUserSettingsQuery.NeedExport ' We need to override MPF's definition of NeedExport since it doesn't know about our automation object needExportParam = If(pageID = "TextEditor.Basic-Specific", 1, 0) Return VSConstants.S_OK End Function Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) End Function Protected Overrides Function CreateEditorFactories() As IEnumerable(Of IVsEditorFactory) Dim editorFactory = New VisualBasicEditorFactory(Me.ComponentModel) Dim codePageEditorFactory = New VisualBasicCodePageEditorFactory(editorFactory) Return {editorFactory, codePageEditorFactory} End Function Protected Overrides Function CreateLanguageService() As VisualBasicLanguageService Return New VisualBasicLanguageService(Me) End Function Protected Overrides Sub RegisterMiscellaneousFilesWorkspaceInformation(miscellaneousFilesWorkspace As MiscellaneousFilesWorkspace) miscellaneousFilesWorkspace.RegisterLanguage( Guids.VisualBasicLanguageServiceId, LanguageNames.VisualBasic, ".vbx") End Sub Protected Overrides ReadOnly Property RoslynLanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop Imports Task = System.Threading.Tasks.Task Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic ' The option page configuration is duplicated in PackageRegistration.pkgdef. ' ' VB option pages tree ' Basic ' General (from editor) ' Scroll Bars (from editor) ' Tabs (from editor) ' Advanced ' Code Style (category) ' General <ProvideLanguageEditorOptionPage(GetType(AdvancedOptionPage), "Basic", Nothing, "Advanced", "#102", 10160)> <ProvideLanguageEditorToolsOptionCategory("Basic", "Code Style", "#109")> <ProvideLanguageEditorOptionPage(GetType(CodeStylePage), "Basic", "Code Style", "General", "#111", 10161)> <ProvideLanguageEditorOptionPage(GetType(NamingStylesOptionPage), "Basic", "Code Style", "Naming", "#110", 10162)> <ProvideLanguageEditorOptionPage(GetType(IntelliSenseOptionPage), "Basic", Nothing, "IntelliSense", "#112", 312)> <Guid(Guids.VisualBasicPackageIdString)> Friend NotInheritable Class VisualBasicPackage Inherits AbstractPackage(Of VisualBasicPackage, VisualBasicLanguageService) Implements IVbCompilerService Implements IVsUserSettingsQuery ' The property page for WinForms project has a special interface that it uses to get ' entry points that are Forms: IVbEntryPointProvider. The semantics for this ' interface are the same as VisualBasicProject::GetFormEntryPoints, but callers get ' the VB Package and cast it to IVbEntryPointProvider. The property page is managed ' and we've redefined the interface, so we have to register a COM aggregate of the ' VB package. This is the same pattern we use for the LanguageService and Razor. Private ReadOnly _comAggregate As Object Private _libraryManager As ObjectBrowserLibraryManager Private _libraryManagerCookie As UInteger Public Sub New() MyBase.New() _comAggregate = Interop.ComAggregate.CreateAggregatedObject(Me) End Sub Protected Overrides Async Function InitializeAsync(cancellationToken As CancellationToken, progress As IProgress(Of ServiceProgressData)) As Task Try Await MyBase.InitializeAsync(cancellationToken, progress).ConfigureAwait(True) Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) RegisterLanguageService(GetType(IVbCompilerService), Function() Task.FromResult(_comAggregate)) RegisterService(Of IVbTempPECompilerFactory)( Async Function(ct) Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(ct) Return New TempPECompilerFactory(workspace) End Function) Catch ex As Exception When FatalError.ReportAndPropagateUnlessCanceled(ex) Throw ExceptionUtilities.Unreachable End Try End Function Protected Overrides Async Function RegisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Dim workspace As VisualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then Me._libraryManager = New ObjectBrowserLibraryManager(Me, ComponentModel, workspace) If ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(Me._libraryManager, Me._libraryManagerCookie)) Then Me._libraryManagerCookie = 0 End If End If End Function Protected Overrides Async Function UnregisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) If _libraryManagerCookie <> 0 Then Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then objectManager.UnregisterLibrary(Me._libraryManagerCookie) Me._libraryManagerCookie = 0 End If Me._libraryManager.Dispose() Me._libraryManager = Nothing End If End Function Public Function NeedExport(pageID As String, <Out> ByRef needExportParam As Integer) As Integer Implements IVsUserSettingsQuery.NeedExport ' We need to override MPF's definition of NeedExport since it doesn't know about our automation object needExportParam = If(pageID = "TextEditor.Basic-Specific", 1, 0) Return VSConstants.S_OK End Function Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) End Function Protected Overrides Function CreateEditorFactories() As IEnumerable(Of IVsEditorFactory) Dim editorFactory = New VisualBasicEditorFactory(Me.ComponentModel) Dim codePageEditorFactory = New VisualBasicCodePageEditorFactory(editorFactory) Return {editorFactory, codePageEditorFactory} End Function Protected Overrides Function CreateLanguageService() As VisualBasicLanguageService Return New VisualBasicLanguageService(Me) End Function Protected Overrides Sub RegisterMiscellaneousFilesWorkspaceInformation(miscellaneousFilesWorkspace As MiscellaneousFilesWorkspace) miscellaneousFilesWorkspace.RegisterLanguage( Guids.VisualBasicLanguageServiceId, LanguageNames.VisualBasic, ".vbx") End Sub Protected Overrides ReadOnly Property RoslynLanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/VisualStudio/Core/Test/ProjectSystemShim/VisualBasicCodeModelLifetimeTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.Shell.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class VisualBasicCodeModelLifetimeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> <Trait(Traits.Feature, Traits.Features.ProjectSystemShims)> <WorkItem(33080, "https://github.com/dotnet/roslyn/issues/33080")> Public Sub RemovingAndReAddingSourceFileWorksCorrectly() Using environment = New TestEnvironment() Dim project = CreateVisualBasicProject(environment, "Test") ' Add the file we're adding and removing to our MockHierarchy, so CodeModel operations correctly work Dim project3 = DirectCast(project.Hierarchy, IVsProject3) project3.AddItem(42, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE, "Z:\SourceFile.vb", Nothing, Nothing, Nothing, Nothing) project.AddFile("Z:\SourceFile.vb", Nothing, False) ' Confirm that we are able to get a file code model Dim originalDocumentId = environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single() Assert.NotNull(originalDocumentId) Dim originalFileCodeModel = environment.Workspace.GetFileCodeModel(originalDocumentId) Assert.NotNull(originalDocumentId) project.RemoveFile("Z:\SourceFile.vb", Nothing) Assert.Throws(Of ArgumentException)(Sub() environment.Workspace.GetFileCodeModel(originalDocumentId)) ' Add it back in project.AddFile("Z:\SourceFile.vb", Nothing, False) Dim newDocumentId = environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single() Dim newFileCodeModel = environment.Workspace.GetFileCodeModel(newDocumentId) Assert.NotSame(originalDocumentId, newDocumentId) Assert.NotSame(originalFileCodeModel, newFileCodeModel) project.Disconnect() End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.Shell.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class VisualBasicCodeModelLifetimeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> <Trait(Traits.Feature, Traits.Features.ProjectSystemShims)> <WorkItem(33080, "https://github.com/dotnet/roslyn/issues/33080")> Public Sub RemovingAndReAddingSourceFileWorksCorrectly() Using environment = New TestEnvironment() Dim project = CreateVisualBasicProject(environment, "Test") ' Add the file we're adding and removing to our MockHierarchy, so CodeModel operations correctly work Dim project3 = DirectCast(project.Hierarchy, IVsProject3) project3.AddItem(42, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE, "Z:\SourceFile.vb", Nothing, Nothing, Nothing, Nothing) project.AddFile("Z:\SourceFile.vb", Nothing, False) ' Confirm that we are able to get a file code model Dim originalDocumentId = environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single() Assert.NotNull(originalDocumentId) Dim originalFileCodeModel = environment.Workspace.GetFileCodeModel(originalDocumentId) Assert.NotNull(originalDocumentId) project.RemoveFile("Z:\SourceFile.vb", Nothing) Assert.Throws(Of ArgumentException)(Sub() environment.Workspace.GetFileCodeModel(originalDocumentId)) ' Add it back in project.AddFile("Z:\SourceFile.vb", Nothing, False) Dim newDocumentId = environment.Workspace.CurrentSolution.Projects.Single().DocumentIds.Single() Dim newFileCodeModel = environment.Workspace.GetFileCodeModel(newDocumentId) Assert.NotSame(originalDocumentId, newDocumentId) Assert.NotSame(originalFileCodeModel, newFileCodeModel) project.Disconnect() End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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.Wpf/ExternalAccess/VSTypeScript/VSTypeScriptSignatureHelpClassifierProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Implementation.IntelliSense.SignatureHelp.Presentation; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Export(typeof(IVSTypeScriptSignatureHelpClassifierProvider))] [Shared] internal sealed class VSTypeScriptSignatureHelpClassifierProvider : IVSTypeScriptSignatureHelpClassifierProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptSignatureHelpClassifierProvider() { } public IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap) => new SignatureHelpClassifier(textBuffer, typeMap); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Editor.Implementation.IntelliSense.SignatureHelp.Presentation; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [Export(typeof(IVSTypeScriptSignatureHelpClassifierProvider))] [Shared] internal sealed class VSTypeScriptSignatureHelpClassifierProvider : IVSTypeScriptSignatureHelpClassifierProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptSignatureHelpClassifierProvider() { } public IClassifier Create(ITextBuffer textBuffer, ClassificationTypeMap typeMap) => new SignatureHelpClassifier(textBuffer, typeMap); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Syntax/Parser/ParseImports.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ParseImports Inherits BasicTestBase <Fact> Public Sub ParseImportsPass() ParseAndVerify(<![CDATA[ Imports System.Text Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic ]]>) ParseAndVerify(<![CDATA[ Imports t1 = System.Text Imports t2 = Microsoft.Languages.Text Imports s1 = Microsoft.VisualBasic.Syntax ]]>) End Sub <Fact> Public Sub BC31398ERR_NoTypecharInAlias_ParseImportsFail() ParseAndVerify(<![CDATA[ Imports s$ = System.Text ]]>, <errors> <error id="31398"/> </errors>) End Sub <Fact> Public Sub BC30203ERR_ExpectedIdentifier_Bug863004() ParseAndVerify(<![CDATA[ Imports (ModImpErrGen003.Scen25) = Default Imports ]]>, <errors> <error id="30193"/> <error id="30203"/> <error id="30203"/> </errors>) End Sub <Fact> Public Sub BC30180ERR_UnrecognizedTypeKeyword_Bug869085() ParseAndVerify(<![CDATA[ imports ns1.GenClass(of of string) ]]>, <errors> <error id="30180"/> </errors>) End Sub <Fact> Public Sub ParseXmlNamespace() ParseAndVerify(<![CDATA[ imports <xmlns:p="ns1"> ]]>) End Sub <Fact> Public Sub ParseXmlNamespaceStart() ParseAndVerify(<![CDATA[ imports < ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "") ) End Sub <Fact> Public Sub BC31187ERR_ExpectedXmlns() ParseAndVerify(<![CDATA[ imports <xml:p="ns1"> ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "xml")) End Sub <Fact> Public Sub BC31187ERR_ExpectedXmlns_2() ParseAndVerify(<![CDATA[ imports <p:xmlns="ns1"> ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "p")) End Sub <WorkItem(879682, "DevDiv/Personal")> <Fact()> Public Sub BC30465ERR_ImportsMustBeFirst() ParseAndVerify(<![CDATA[ Class Class1 End Class Imports System ]]>, <errors> <error id="30465"/> </errors>) End Sub <WorkItem(541486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541486")> <Fact> Public Sub ImportsAliasMissingIdentifier() Dim tree = ParseAndVerify(<![CDATA[ Imports = System ]]>, <errors> <error id="30203"/> </errors>) VerifySyntaxKinds(tree.GetRoot().DescendantNodes.OfType(Of ImportsStatementSyntax).First, SyntaxKind.ImportsStatement, SyntaxKind.ImportsKeyword, SyntaxKind.SimpleImportsClause, SyntaxKind.ImportAliasClause, SyntaxKind.IdentifierToken, SyntaxKind.EqualsToken, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken) End Sub <WorkItem(541486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541486")> <Fact()> Public Sub ImportsMissingIdentifierBeforeComma() Dim tree = ParseAndVerify(<![CDATA[ Imports ,System ]]>, <errors> <error id="30203"/> </errors>) VerifySyntaxKinds(tree.GetRoot().DescendantNodes.OfType(Of ImportsStatementSyntax).First, SyntaxKind.ImportsStatement, SyntaxKind.ImportsKeyword, SyntaxKind.SimpleImportsClause, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken, SyntaxKind.CommaToken, SyntaxKind.SimpleImportsClause, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken) End Sub <WorkItem(541803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541803")> <Fact> Public Sub AnotherImportsAfterComma() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Collections.Generic, System ' no errors here Imports System.Collections, Imports System ]]>, <errors> <error id="30183"/> </errors>) End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities <CLSCompliant(False)> Public Class ParseImports Inherits BasicTestBase <Fact> Public Sub ParseImportsPass() ParseAndVerify(<![CDATA[ Imports System.Text Imports Roslyn.Compilers Imports Roslyn.Compilers.Common Imports Roslyn.Compilers.VisualBasic ]]>) ParseAndVerify(<![CDATA[ Imports t1 = System.Text Imports t2 = Microsoft.Languages.Text Imports s1 = Microsoft.VisualBasic.Syntax ]]>) End Sub <Fact> Public Sub BC31398ERR_NoTypecharInAlias_ParseImportsFail() ParseAndVerify(<![CDATA[ Imports s$ = System.Text ]]>, <errors> <error id="31398"/> </errors>) End Sub <Fact> Public Sub BC30203ERR_ExpectedIdentifier_Bug863004() ParseAndVerify(<![CDATA[ Imports (ModImpErrGen003.Scen25) = Default Imports ]]>, <errors> <error id="30193"/> <error id="30203"/> <error id="30203"/> </errors>) End Sub <Fact> Public Sub BC30180ERR_UnrecognizedTypeKeyword_Bug869085() ParseAndVerify(<![CDATA[ imports ns1.GenClass(of of string) ]]>, <errors> <error id="30180"/> </errors>) End Sub <Fact> Public Sub ParseXmlNamespace() ParseAndVerify(<![CDATA[ imports <xmlns:p="ns1"> ]]>) End Sub <Fact> Public Sub ParseXmlNamespaceStart() ParseAndVerify(<![CDATA[ imports < ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "") ) End Sub <Fact> Public Sub BC31187ERR_ExpectedXmlns() ParseAndVerify(<![CDATA[ imports <xml:p="ns1"> ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "xml")) End Sub <Fact> Public Sub BC31187ERR_ExpectedXmlns_2() ParseAndVerify(<![CDATA[ imports <p:xmlns="ns1"> ]]>, Diagnostic(ERRID.ERR_ExpectedXmlns, ""), Diagnostic(ERRID.ERR_ExpectedGreater, "p")) End Sub <WorkItem(879682, "DevDiv/Personal")> <Fact()> Public Sub BC30465ERR_ImportsMustBeFirst() ParseAndVerify(<![CDATA[ Class Class1 End Class Imports System ]]>, <errors> <error id="30465"/> </errors>) End Sub <WorkItem(541486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541486")> <Fact> Public Sub ImportsAliasMissingIdentifier() Dim tree = ParseAndVerify(<![CDATA[ Imports = System ]]>, <errors> <error id="30203"/> </errors>) VerifySyntaxKinds(tree.GetRoot().DescendantNodes.OfType(Of ImportsStatementSyntax).First, SyntaxKind.ImportsStatement, SyntaxKind.ImportsKeyword, SyntaxKind.SimpleImportsClause, SyntaxKind.ImportAliasClause, SyntaxKind.IdentifierToken, SyntaxKind.EqualsToken, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken) End Sub <WorkItem(541486, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541486")> <Fact()> Public Sub ImportsMissingIdentifierBeforeComma() Dim tree = ParseAndVerify(<![CDATA[ Imports ,System ]]>, <errors> <error id="30203"/> </errors>) VerifySyntaxKinds(tree.GetRoot().DescendantNodes.OfType(Of ImportsStatementSyntax).First, SyntaxKind.ImportsStatement, SyntaxKind.ImportsKeyword, SyntaxKind.SimpleImportsClause, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken, SyntaxKind.CommaToken, SyntaxKind.SimpleImportsClause, SyntaxKind.IdentifierName, SyntaxKind.IdentifierToken) End Sub <WorkItem(541803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541803")> <Fact> Public Sub AnotherImportsAfterComma() Dim tree = ParseAndVerify(<![CDATA[ Imports System.Collections.Generic, System ' no errors here Imports System.Collections, Imports System ]]>, <errors> <error id="30183"/> </errors>) End Sub End Class
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/Source/SourceDestructorSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceDestructorSymbol : SourceMemberMethodSymbol { private TypeWithAnnotations _lazyReturnType; private readonly bool _isExpressionBodied; internal SourceDestructorSymbol( SourceMemberContainerTypeSymbol containingType, DestructorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), syntax.Identifier.GetLocation(), isIterator: SyntaxFacts.HasYieldOperations(syntax.Body)) { const MethodKind methodKind = MethodKind.Destructor; Location location = this.Locations[0]; bool modifierErrors; var declarationModifiers = MakeModifiers(syntax.Modifiers, location, diagnostics, out modifierErrors); this.MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled); if (syntax.Identifier.ValueText != containingType.Name) { diagnostics.Add(ErrorCode.ERR_BadDestructorName, syntax.Identifier.GetLocation()); } bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; if (hasBlockBody || _isExpressionBodied) { if (IsExtern) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } } if (!modifierErrors && !hasBlockBody && !_isExpressionBodied && !IsExtern) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } Debug.Assert(syntax.ParameterList.Parameters.Count == 0); if (containingType.IsStatic) { diagnostics.Add(ErrorCode.ERR_DestructorInStaticClass, location, this); } else if (!containingType.IsReferenceType) { diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, location, this); } CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var bodyBinder = this.DeclaringCompilation.GetBinderFactory(syntaxReferenceOpt.SyntaxTree).GetBinder(syntax, syntax, this); _lazyReturnType = TypeWithAnnotations.Create(bodyBinder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax)); } internal DestructorDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (DestructorDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } public override bool IsVararg { get { return false; } } internal override int ParameterCount { get { return 0; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) { // Check that the set of modifiers is allowed const DeclarationModifiers allowedModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Unsafe; var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, DeclarationModifiers.None, allowedModifiers, location, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Protected; // we mark destructors protected in the symbol table return mods; } public override string Name { get { return WellKnownMemberNames.DestructorName; } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // destructors can't have return type attributes return OneOrMany.Create(this.GetSyntax().AttributeLists); } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // destructors can't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return (object)this.ContainingType.BaseTypeNoUseSiteDiagnostics == null; } internal override bool GenerateDebugInfo { get { 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.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SourceDestructorSymbol : SourceMemberMethodSymbol { private TypeWithAnnotations _lazyReturnType; private readonly bool _isExpressionBodied; internal SourceDestructorSymbol( SourceMemberContainerTypeSymbol containingType, DestructorDeclarationSyntax syntax, bool isNullableAnalysisEnabled, BindingDiagnosticBag diagnostics) : base(containingType, syntax.GetReference(), syntax.Identifier.GetLocation(), isIterator: SyntaxFacts.HasYieldOperations(syntax.Body)) { const MethodKind methodKind = MethodKind.Destructor; Location location = this.Locations[0]; bool modifierErrors; var declarationModifiers = MakeModifiers(syntax.Modifiers, location, diagnostics, out modifierErrors); this.MakeFlags(methodKind, declarationModifiers, returnsVoid: true, isExtensionMethod: false, isNullableAnalysisEnabled: isNullableAnalysisEnabled); if (syntax.Identifier.ValueText != containingType.Name) { diagnostics.Add(ErrorCode.ERR_BadDestructorName, syntax.Identifier.GetLocation()); } bool hasBlockBody = syntax.Body != null; _isExpressionBodied = !hasBlockBody && syntax.ExpressionBody != null; if (hasBlockBody || _isExpressionBodied) { if (IsExtern) { diagnostics.Add(ErrorCode.ERR_ExternHasBody, location, this); } } if (!modifierErrors && !hasBlockBody && !_isExpressionBodied && !IsExtern) { diagnostics.Add(ErrorCode.ERR_ConcreteMissingBody, location, this); } Debug.Assert(syntax.ParameterList.Parameters.Count == 0); if (containingType.IsStatic) { diagnostics.Add(ErrorCode.ERR_DestructorInStaticClass, location, this); } else if (!containingType.IsReferenceType) { diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, location, this); } CheckForBlockAndExpressionBody( syntax.Body, syntax.ExpressionBody, syntax, diagnostics); } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { var syntax = GetSyntax(); var bodyBinder = this.DeclaringCompilation.GetBinderFactory(syntaxReferenceOpt.SyntaxTree).GetBinder(syntax, syntax, this); _lazyReturnType = TypeWithAnnotations.Create(bodyBinder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax)); } internal DestructorDeclarationSyntax GetSyntax() { Debug.Assert(syntaxReferenceOpt != null); return (DestructorDeclarationSyntax)syntaxReferenceOpt.GetSyntax(); } public override bool IsVararg { get { return false; } } internal override int ParameterCount { get { return 0; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { LazyMethodChecks(); return _lazyReturnType; } } private DeclarationModifiers MakeModifiers(SyntaxTokenList modifiers, Location location, BindingDiagnosticBag diagnostics, out bool modifierErrors) { // Check that the set of modifiers is allowed const DeclarationModifiers allowedModifiers = DeclarationModifiers.Extern | DeclarationModifiers.Unsafe; var mods = ModifierUtils.MakeAndCheckNontypeMemberModifiers(modifiers, DeclarationModifiers.None, allowedModifiers, location, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); mods = (mods & ~DeclarationModifiers.AccessibilityMask) | DeclarationModifiers.Protected; // we mark destructors protected in the symbol table return mods; } public override string Name { get { return WellKnownMemberNames.DestructorName; } } internal override bool IsExpressionBodied { get { return _isExpressionBodied; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // destructors can't have return type attributes return OneOrMany.Create(this.GetSyntax().AttributeLists); } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // destructors can't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return (object)this.ContainingType.BaseTypeNoUseSiteDiagnostics == null; } internal override bool GenerateDebugInfo { get { return true; } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/LiveShare/Impl/Client/Projects/IRemoteProjectInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Projects { internal interface IRemoteProjectInfoProvider { Task<ImmutableArray<ProjectInfo>> GetRemoteProjectInfosAsync(CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Utilities/CSharp/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public static class SyntaxTreeExtensions { public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int offset, int length, string newText) { var oldFullText = syntaxTree.GetText(); var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText)); return syntaxTree.WithChangedText(newFullText); } public static SyntaxTree WithReplaceFirst(this SyntaxTree syntaxTree, string oldText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal); int length = oldText.Length; return WithReplace(syntaxTree, offset, length, newText); } public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int startIndex, string oldText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(oldText, startIndex, StringComparison.Ordinal); // Use an offset to find the first element to replace at int length = oldText.Length; return WithReplace(syntaxTree, offset, length, newText); } public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText) { return WithReplace(syntaxTree, offset, 0, newText); } public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(existingText, StringComparison.Ordinal); return WithReplace(syntaxTree, offset, 0, newText); } public static SyntaxTree WithRemoveAt(this SyntaxTree syntaxTree, int offset, int length) { return WithReplace(syntaxTree, offset, length, string.Empty); } public static SyntaxTree WithRemoveFirst(this SyntaxTree syntaxTree, string oldText) { return WithReplaceFirst(syntaxTree, oldText, string.Empty); } internal static string Dump(this SyntaxNode node) { var visitor = new CSharpSyntaxPrinter(); visitor.Visit(node); return visitor.Dump(); } internal static string Dump(this SyntaxTree tree) { return tree.GetRoot().Dump(); } private class CSharpSyntaxPrinter : CSharpSyntaxWalker { readonly PooledStringBuilder builder; int indent = 0; internal CSharpSyntaxPrinter() { builder = PooledStringBuilder.GetInstance(); } internal string Dump() { return builder.ToStringAndFree(); } public override void DefaultVisit(SyntaxNode node) { builder.Builder.Append(' ', repeatCount: indent); builder.Builder.Append(node.Kind().ToString()); if (node.IsMissing) { builder.Builder.Append(" (missing)"); } else if (node is IdentifierNameSyntax name) { builder.Builder.Append(" "); builder.Builder.Append(name.ToString()); } builder.Builder.AppendLine(); indent += 2; base.DefaultVisit(node); indent -= 2; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public static class SyntaxTreeExtensions { public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int offset, int length, string newText) { var oldFullText = syntaxTree.GetText(); var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText)); return syntaxTree.WithChangedText(newFullText); } public static SyntaxTree WithReplaceFirst(this SyntaxTree syntaxTree, string oldText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal); int length = oldText.Length; return WithReplace(syntaxTree, offset, length, newText); } public static SyntaxTree WithReplace(this SyntaxTree syntaxTree, int startIndex, string oldText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(oldText, startIndex, StringComparison.Ordinal); // Use an offset to find the first element to replace at int length = oldText.Length; return WithReplace(syntaxTree, offset, length, newText); } public static SyntaxTree WithInsertAt(this SyntaxTree syntaxTree, int offset, string newText) { return WithReplace(syntaxTree, offset, 0, newText); } public static SyntaxTree WithInsertBefore(this SyntaxTree syntaxTree, string existingText, string newText) { var oldFullText = syntaxTree.GetText().ToString(); int offset = oldFullText.IndexOf(existingText, StringComparison.Ordinal); return WithReplace(syntaxTree, offset, 0, newText); } public static SyntaxTree WithRemoveAt(this SyntaxTree syntaxTree, int offset, int length) { return WithReplace(syntaxTree, offset, length, string.Empty); } public static SyntaxTree WithRemoveFirst(this SyntaxTree syntaxTree, string oldText) { return WithReplaceFirst(syntaxTree, oldText, string.Empty); } internal static string Dump(this SyntaxNode node) { var visitor = new CSharpSyntaxPrinter(); visitor.Visit(node); return visitor.Dump(); } internal static string Dump(this SyntaxTree tree) { return tree.GetRoot().Dump(); } private class CSharpSyntaxPrinter : CSharpSyntaxWalker { readonly PooledStringBuilder builder; int indent = 0; internal CSharpSyntaxPrinter() { builder = PooledStringBuilder.GetInstance(); } internal string Dump() { return builder.ToStringAndFree(); } public override void DefaultVisit(SyntaxNode node) { builder.Builder.Append(' ', repeatCount: indent); builder.Builder.Append(node.Kind().ToString()); if (node.IsMissing) { builder.Builder.Append(" (missing)"); } else if (node is IdentifierNameSyntax name) { builder.Builder.Append(" "); builder.Builder.Append(name.ToString()); } builder.Builder.AppendLine(); indent += 2; base.DefaultVisit(node); indent -= 2; } } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/CodeCleanup/CSharpCodeCleanerServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeCleanup; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { [ExportLanguageServiceFactory(typeof(ICodeCleanerService), LanguageNames.CSharp), Shared] internal class CSharpCodeCleanerServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanerServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeCleanerService(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeCleanup; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeCleanup { [ExportLanguageServiceFactory(typeof(ICodeCleanerService), LanguageNames.CSharp), Shared] internal class CSharpCodeCleanerServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeCleanerServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeCleanerService(); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Features/Core/Portable/CodeFixes/Configuration/ConfigureSeverity/ConfigureSeverityLevelCodeFixProvider.TopLevelBulkConfigureSeverityCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; namespace Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity { internal sealed partial class ConfigureSeverityLevelCodeFixProvider : IConfigurationFixProvider { private sealed class TopLevelBulkConfigureSeverityCodeAction : AbstractConfigurationActionWithNestedActions { public TopLevelBulkConfigureSeverityCodeAction(ImmutableArray<CodeAction> nestedActions, string? category) : base(nestedActions, category != null ? string.Format(FeaturesResources.Configure_severity_for_all_0_analyzers, category) : FeaturesResources.Configure_severity_for_all_analyzers) { // Ensure that 'Category' based bulk configuration actions are shown above // the 'All analyzer diagnostics' bulk configuration actions. AdditionalPriority = category != null ? CodeActionPriority.Low : CodeActionPriority.Lowest; } internal override CodeActionPriority AdditionalPriority { get; } internal override bool IsBulkConfigurationAction => true; } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/LongTypeFormInSignature.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // 1) csc /target:library LongTypeFormInSignature.cs // 2) open in a binary editor and replace "Attribute" with "String\0\0\0" and "DateTime" with "Double\0\0" (the only occurrence should be in the #String heap). public class C { public static System.Attribute RT() { return null; } public static System.DateTime VT() { return default(System.DateTime); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // 1) csc /target:library LongTypeFormInSignature.cs // 2) open in a binary editor and replace "Attribute" with "String\0\0\0" and "DateTime" with "Double\0\0" (the only occurrence should be in the #String heap). public class C { public static System.Attribute RT() { return null; } public static System.DateTime VT() { return default(System.DateTime); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.es.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="es" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Agregar "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Convertir "typeof" en "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Pasar variables capturadas como argumentos</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Colocar dos puntos en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Instrucción de colocación en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Eliminar instrucciones Using innecesarias</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Quitar línea en blanco entre llaves</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Quitar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Advertencia: Agregar parámetros a la declaración de función local puede generar código no válido.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Agregar "this."</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Convertir "typeof" en "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Pasar variables capturadas como argumentos</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Colocar dos puntos en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Instrucción de colocación en la línea siguiente</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Eliminar instrucciones Using innecesarias</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Quitar línea en blanco entre llaves</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Quitar código inaccesible</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Advertencia: Agregar parámetros a la declaración de función local puede generar código no válido.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/ExpressionEvaluator/VisualBasic/Source/ResultProvider/Helpers/TypeExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type Imports TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module TypeExtensions <Extension> Public Function IsPredefinedType(type As Type) As Boolean Return type.GetPredefinedTypeName() IsNot Nothing End Function <Extension> Public Function GetPredefinedTypeName(type As Type) As String If type.IsEnum Then Return Nothing End If Select Case Type.GetTypeCode(type) Case TypeCode.Object Return If(type.IsObject(), "Object", Nothing) Case TypeCode.Boolean Return "Boolean" Case TypeCode.Char Return "Char" Case TypeCode.SByte Return "SByte" Case TypeCode.Byte Return "Byte" Case TypeCode.Int16 Return "Short" Case TypeCode.UInt16 Return "UShort" Case TypeCode.Int32 Return "Integer" Case TypeCode.UInt32 Return "UInteger" Case TypeCode.Int64 Return "Long" Case TypeCode.UInt64 Return "ULong" Case TypeCode.Single Return "Single" Case TypeCode.Double Return "Double" Case TypeCode.Decimal Return "Decimal" Case TypeCode.String Return "String" Case TypeCode.DateTime Return "Date" End Select Return Nothing End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Type = Microsoft.VisualStudio.Debugger.Metadata.Type Imports TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module TypeExtensions <Extension> Public Function IsPredefinedType(type As Type) As Boolean Return type.GetPredefinedTypeName() IsNot Nothing End Function <Extension> Public Function GetPredefinedTypeName(type As Type) As String If type.IsEnum Then Return Nothing End If Select Case Type.GetTypeCode(type) Case TypeCode.Object Return If(type.IsObject(), "Object", Nothing) Case TypeCode.Boolean Return "Boolean" Case TypeCode.Char Return "Char" Case TypeCode.SByte Return "SByte" Case TypeCode.Byte Return "Byte" Case TypeCode.Int16 Return "Short" Case TypeCode.UInt16 Return "UShort" Case TypeCode.Int32 Return "Integer" Case TypeCode.UInt32 Return "UInteger" Case TypeCode.Int64 Return "Long" Case TypeCode.UInt64 Return "ULong" Case TypeCode.Single Return "Single" Case TypeCode.Double Return "Double" Case TypeCode.Decimal Return "Decimal" Case TypeCode.String Return "String" Case TypeCode.DateTime Return "Date" End Select Return Nothing End Function End Module End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Venus/IVsContainedLanguageCodeSupport.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetMembers and GetCompatibleEventMembers, because they take optional out /// params, and the marshalling was wrong in the PIA. /// </summary> [ComImport, ComConversionLoss, InterfaceType(1), Guid("F386BE91-0E80-43AF-8EB6-8B829FA06282")] internal interface IVsContainedLanguageCodeSupport { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int CreateUniqueEventName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventHandlerName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMemberNavigationPoint( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanNavPoint, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] out uint pItemID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMembers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwFlags, out int pcMembers, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int OnRenamed( [In, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.ContainedLanguageRenameType")] ContainedLanguageRenameType clrt, [In, MarshalAs(UnmanagedType.BStr)] string bstrOldID, [In, MarshalAs(UnmanagedType.BStr)] string bstrNewID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int IsValidID( [In, MarshalAs(UnmanagedType.BStr)] string bstrID, out bool pfIsValidID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetBaseClassName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [MarshalAs(UnmanagedType.BStr)] out string pbstrBaseClassName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetEventHandlerMemberID( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetCompatibleEventHandlers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, out int pcMembers, IntPtr ppbstrEventHandlerNames, IntPtr ppbstrMemberIDs); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// This interface is redefined by copy/paste from Reflector, so that we can tweak the /// definitions of GetMembers and GetCompatibleEventMembers, because they take optional out /// params, and the marshalling was wrong in the PIA. /// </summary> [ComImport, ComConversionLoss, InterfaceType(1), Guid("F386BE91-0E80-43AF-8EB6-8B829FA06282")] internal interface IVsContainedLanguageCodeSupport { [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int CreateUniqueEventName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventHandlerName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int EnsureEventHandler( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [In, ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] uint itemidInsertionPoint, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID, [MarshalAs(UnmanagedType.BStr)] out string pbstrEventBody, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanInsertionPoint); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMemberNavigationPoint( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszUniqueMemberID, [Out, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan"), MarshalAs(UnmanagedType.LPArray)] TextSpan[] pSpanNavPoint, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")] out uint pItemID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetMembers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")] uint dwFlags, out int pcMembers, IntPtr ppbstrDisplayNames, IntPtr ppbstrMemberIDs); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int OnRenamed( [In, ComAliasName("Microsoft.VisualStudio.TextManager.Interop.ContainedLanguageRenameType")] ContainedLanguageRenameType clrt, [In, MarshalAs(UnmanagedType.BStr)] string bstrOldID, [In, MarshalAs(UnmanagedType.BStr)] string bstrNewID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int IsValidID( [In, MarshalAs(UnmanagedType.BStr)] string bstrID, out bool pfIsValidID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetBaseClassName( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [MarshalAs(UnmanagedType.BStr)] out string pbstrBaseClassName); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetEventHandlerMemberID( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszEventHandlerName, [MarshalAs(UnmanagedType.BStr)] out string pbstrUniqueMemberID); [PreserveSig, MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] int GetCompatibleEventHandlers( [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszClassName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszObjectTypeName, [In, ComAliasName("Microsoft.VisualStudio.OLE.Interop.LPCWSTR"), MarshalAs(UnmanagedType.LPWStr)] string pszNameOfEvent, out int pcMembers, IntPtr ppbstrEventHandlerNames, IntPtr ppbstrMemberIDs); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/BoundTree/NoOpStatementFlavor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp { internal enum NoOpStatementFlavor { Default, // <summary> // Marks a control yield point for emitted await operator; is processed by codegen; // only allowed inside MoveNext methods generated for Async methods // </summary> AwaitYieldPoint, // <summary> // Marks a control resume point for emitted await operator; is processed by codegen; // only allowed inside MoveNext methods generated for Async methods // </summary> AwaitResumePoint } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.CSharp { internal enum NoOpStatementFlavor { Default, // <summary> // Marks a control yield point for emitted await operator; is processed by codegen; // only allowed inside MoveNext methods generated for Async methods // </summary> AwaitYieldPoint, // <summary> // Marks a control resume point for emitted await operator; is processed by codegen; // only allowed inside MoveNext methods generated for Async methods // </summary> AwaitResumePoint } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Workspaces/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDocumentationCommentWrapper.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Shared.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal readonly struct VSTypeScriptDocumentationCommentWrapper { private readonly DocumentationComment _underlyingObject; public VSTypeScriptDocumentationCommentWrapper(DocumentationComment underlyingObject) => _underlyingObject = underlyingObject; public static VSTypeScriptDocumentationCommentWrapper FromXmlFragment(string xml) => new(DocumentationComment.FromXmlFragment(xml)); public bool IsDefault => _underlyingObject == null; public string? SummaryTextOpt => _underlyingObject?.SummaryText; public string? GetParameterTextOpt(string parameterName) => _underlyingObject?.GetParameterText(parameterName); } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./docs/features/local-functions.work.md
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introduces compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introduces compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Providers/CompletionLinkedFilesSymbolEquivalenceComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Shared.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> { private sealed class CompletionLinkedFilesSymbolEquivalenceComparer : IEqualityComparer<(ISymbol symbol, bool preselect)> { public static readonly CompletionLinkedFilesSymbolEquivalenceComparer Instance = new(); public bool Equals((ISymbol symbol, bool preselect) x, (ISymbol symbol, bool preselect) y) => LinkedFilesSymbolEquivalenceComparer.Instance.Equals(x.symbol, y.symbol); public int GetHashCode((ISymbol symbol, bool preselect) obj) => LinkedFilesSymbolEquivalenceComparer.Instance.GetHashCode(obj.symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Shared.Utilities; namespace Microsoft.CodeAnalysis.Completion.Providers { internal abstract partial class AbstractSymbolCompletionProvider<TSyntaxContext> { private sealed class CompletionLinkedFilesSymbolEquivalenceComparer : IEqualityComparer<(ISymbol symbol, bool preselect)> { public static readonly CompletionLinkedFilesSymbolEquivalenceComparer Instance = new(); public bool Equals((ISymbol symbol, bool preselect) x, (ISymbol symbol, bool preselect) y) => LinkedFilesSymbolEquivalenceComparer.Instance.Equals(x.symbol, y.symbol); public int GetHashCode((ISymbol symbol, bool preselect) obj) => LinkedFilesSymbolEquivalenceComparer.Instance.GetHashCode(obj.symbol); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Workspace/Core/Extensions/HostWorkspaceServicesExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Host { internal static class HostWorkspaceServicesExtensions { public static TLanguageService? GetLanguageService<TLanguageService>(this HostWorkspaceServices hostWorkspaceServices, string languageName) where TLanguageService : class, ILanguageService => hostWorkspaceServices?.GetExtendedLanguageServices(languageName).GetService<TLanguageService>(); public static TLanguageService GetRequiredLanguageService<TLanguageService>(this HostWorkspaceServices hostWorkspaceServices, string languageName) where TLanguageService : class, ILanguageService => hostWorkspaceServices.GetExtendedLanguageServices(languageName).GetRequiredService<TLanguageService>(); #pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allow in this helper which computes the extended language services. /// <summary> /// Gets extended host language services, which includes language services from <see cref="HostWorkspaceServices.GetLanguageServices(string)"/>. /// </summary> public static HostLanguageServices GetExtendedLanguageServices(this HostWorkspaceServices hostWorkspaceServices, string languageName) { var languageServices = hostWorkspaceServices.GetLanguageServices(languageName); #if CODE_STYLE languageServices = CodeStyleHostLanguageServices.GetRequiredMappedCodeStyleLanguageServices(languageServices); #endif return languageServices; } #pragma warning restore RS0030 // Do not used banned APIs } }
// Licensed to the .NET Foundation under one or more 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.Host { internal static class HostWorkspaceServicesExtensions { public static TLanguageService? GetLanguageService<TLanguageService>(this HostWorkspaceServices hostWorkspaceServices, string languageName) where TLanguageService : class, ILanguageService => hostWorkspaceServices?.GetExtendedLanguageServices(languageName).GetService<TLanguageService>(); public static TLanguageService GetRequiredLanguageService<TLanguageService>(this HostWorkspaceServices hostWorkspaceServices, string languageName) where TLanguageService : class, ILanguageService => hostWorkspaceServices.GetExtendedLanguageServices(languageName).GetRequiredService<TLanguageService>(); #pragma warning disable RS0030 // Do not used banned API 'GetLanguageServices', use 'GetExtendedLanguageServices' instead - allow in this helper which computes the extended language services. /// <summary> /// Gets extended host language services, which includes language services from <see cref="HostWorkspaceServices.GetLanguageServices(string)"/>. /// </summary> public static HostLanguageServices GetExtendedLanguageServices(this HostWorkspaceServices hostWorkspaceServices, string languageName) { var languageServices = hostWorkspaceServices.GetLanguageServices(languageName); #if CODE_STYLE languageServices = CodeStyleHostLanguageServices.GetRequiredMappedCodeStyleLanguageServices(languageServices); #endif return languageServices; } #pragma warning restore RS0030 // Do not used banned APIs } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/IntegrationService/IntegrationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Reflection; using System.Runtime.Remoting; namespace Microsoft.VisualStudio.IntegrationTest.Utilities { /// <summary> /// Provides a means of executing code in the Visual Studio host process. /// </summary> /// <remarks> /// This object exists in the Visual Studio host and is marhsalled across the process boundary. /// </remarks> internal class IntegrationService : MarshalByRefObject { public string PortName { get; } /// <summary> /// The base Uri of the service. This resolves to a string such as <c>ipc://IntegrationService_{HostProcessId}"</c> /// </summary> public string BaseUri { get; } private readonly ConcurrentDictionary<string, ObjRef> _marshalledObjects = new ConcurrentDictionary<string, ObjRef>(); public IntegrationService() { AppContext.SetSwitch("Switch.System.Diagnostics.IgnorePortablePDBsInStackTraces", false); PortName = GetPortName(Process.GetCurrentProcess().Id); BaseUri = "ipc://" + this.PortName; } private static string GetPortName(int hostProcessId) { // Make the channel name well-known by using a static base and appending the process ID of the host return $"{nameof(IntegrationService)}_{{{hostProcessId}}}"; } public static IntegrationService GetInstanceFromHostProcess(Process hostProcess) { var uri = $"ipc://{GetPortName(hostProcess.Id)}/{typeof(IntegrationService).FullName}"; return (IntegrationService)Activator.GetObject(typeof(IntegrationService), uri); } public string? Execute(string assemblyFilePath, string typeFullName, string methodName) { var assembly = Assembly.LoadFrom(assemblyFilePath); var type = assembly.GetType(typeFullName); var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); var result = methodInfo.Invoke(null, null); if (methodInfo.ReturnType == typeof(void)) { return null; } // Create a unique URL for each object returned, so that we can communicate with each object individually var resultType = result.GetType(); var marshallableResult = (MarshalByRefObject)result; var objectUri = $"{resultType.FullName}_{Guid.NewGuid()}"; var marshalledObject = RemotingServices.Marshal(marshallableResult, objectUri, resultType); if (!_marshalledObjects.TryAdd(objectUri, marshalledObject)) { throw new InvalidOperationException($"An object with the specified URI has already been marshalled. (URI: {objectUri})"); } return objectUri; } // Ensure InProcComponents live forever public override object? InitializeLifetimeService() => null; } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/Host/RemoteDocumentDifferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Provide document difference service specific to remote workspace's behavior. /// /// Default <see cref="AbstractDocumentDifferenceService"/> is optimized for typing case in editor where we have events /// for each typing. But in remote workspace, we aggregate changes and update solution in bulk and we don't have concept /// of active file making default implementation unsuitable. Functionally, default one is still correct, but it often /// time makes us to do more than we need. Basically, it always says this project has semantic change which can cause /// a lot of re-analysis. /// </summary> internal class RemoteDocumentDifferenceService : IDocumentDifferenceService { [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.CSharp, layer: WorkspaceKind.Host), Shared] internal sealed class CSharpDocumentDifferenceService : RemoteDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentDifferenceService() { } } [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.VisualBasic, layer: WorkspaceKind.Host), Shared] internal sealed class VisualBasicDocumentDifferenceService : AbstractDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicDocumentDifferenceService() { } } public async Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { // in remote workspace, we don't trust any version based on VersionStamp. we only trust content based information such as // checksum or tree comparison and etc. // first check checksum var oldTextChecksum = (await oldDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; var newTextChecksum = (await newDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; if (oldTextChecksum == newTextChecksum) { // null means nothing has changed. return null; } var oldRoot = await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // the service is only registered for C# and VB documents, which must have syntax trees: Contract.ThrowIfNull(oldRoot); Contract.ThrowIfNull(newRoot); if (oldRoot.IsEquivalentTo(newRoot, topLevel: true)) { // only method body changed return new DocumentDifferenceResult(InvocationReasons.SyntaxChanged); } // semantic has changed as well. return new DocumentDifferenceResult(InvocationReasons.DocumentChanged); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host.Mef; using Microsoft.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Provide document difference service specific to remote workspace's behavior. /// /// Default <see cref="AbstractDocumentDifferenceService"/> is optimized for typing case in editor where we have events /// for each typing. But in remote workspace, we aggregate changes and update solution in bulk and we don't have concept /// of active file making default implementation unsuitable. Functionally, default one is still correct, but it often /// time makes us to do more than we need. Basically, it always says this project has semantic change which can cause /// a lot of re-analysis. /// </summary> internal class RemoteDocumentDifferenceService : IDocumentDifferenceService { [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.CSharp, layer: WorkspaceKind.Host), Shared] internal sealed class CSharpDocumentDifferenceService : RemoteDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentDifferenceService() { } } [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.VisualBasic, layer: WorkspaceKind.Host), Shared] internal sealed class VisualBasicDocumentDifferenceService : AbstractDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicDocumentDifferenceService() { } } public async Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { // in remote workspace, we don't trust any version based on VersionStamp. we only trust content based information such as // checksum or tree comparison and etc. // first check checksum var oldTextChecksum = (await oldDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; var newTextChecksum = (await newDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; if (oldTextChecksum == newTextChecksum) { // null means nothing has changed. return null; } var oldRoot = await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // the service is only registered for C# and VB documents, which must have syntax trees: Contract.ThrowIfNull(oldRoot); Contract.ThrowIfNull(newRoot); if (oldRoot.IsEquivalentTo(newRoot, topLevel: true)) { // only method body changed return new DocumentDifferenceResult(InvocationReasons.SyntaxChanged); } // semantic has changed as well. return new DocumentDifferenceResult(InvocationReasons.DocumentChanged); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/SpecialTypeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class SpecialTypeExtensions { public static bool CanBeConst(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_String: return true; default: return false; } } public static bool IsValidVolatileFieldType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Char: case SpecialType.System_Single: case SpecialType.System_Boolean: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return true; default: return false; } } public static int FixedBufferElementSizeInBytes(this SpecialType specialType) { // SizeInBytes() handles decimal (contrary to the language spec). But decimal is not allowed // as a fixed buffer element type. return specialType == SpecialType.System_Decimal ? 0 : specialType.SizeInBytes(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal static class SpecialTypeExtensions { public static bool CanBeConst(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Boolean: case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_String: return true; default: return false; } } public static bool IsValidVolatileFieldType(this SpecialType specialType) { switch (specialType) { case SpecialType.System_Byte: case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Char: case SpecialType.System_Single: case SpecialType.System_Boolean: case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return true; default: return false; } } public static int FixedBufferElementSizeInBytes(this SpecialType specialType) { // SizeInBytes() handles decimal (contrary to the language spec). But decimal is not allowed // as a fixed buffer element type. return specialType == SpecialType.System_Decimal ? 0 : specialType.SizeInBytes(); } } }
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
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/SymbolDisplay/SymbolDisplayVisitor_Minimal.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class SymbolDisplayVisitor Protected Overrides Function ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes() As Boolean Dim token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt) Dim startNode = token.Parent Return SyntaxFacts.IsInNamespaceOrTypeContext(TryCast(startNode, ExpressionSyntax)) OrElse Me.inNamespaceOrType End Function Private Sub MinimallyQualify(symbol As INamespaceSymbol, emittedName As String, parentsEmittedName As String) Debug.Assert(symbol.ContainingNamespace IsNot Nothing OrElse symbol.IsGlobalNamespace) ' NOTE(cyrusn): We only call this once we've already checked if there is an alias that ' corresponds to this namespace. If symbol.IsGlobalNamespace Then ' nothing to add for global namespace itself Return End If Dim visitedParent = False ' Check if the name of this namespace binds to the same namespace symbol. If so, ' then that's all we need to add. Otherwise, we will add the minimally qualified ' version of our parent, and then add ourselves to that. Dim symbols = If( ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes(), semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name:=symbol.Name), semanticModelOpt.LookupSymbols(positionOpt, name:=symbol.Name)) Dim lookupResult As NamespaceSymbol = Nothing If symbols.Length = 1 Then lookupResult = TryCast(symbols(0), NamespaceSymbol) End If ' It is possible to get NamespaceSymbol with compilation extent here. ' Let's check this case. If lookupResult IsNot Nothing Then Debug.Assert(lookupResult.Extent.Kind = NamespaceKind.Module OrElse lookupResult.Extent.Kind = NamespaceKind.Compilation) If lookupResult IsNot symbol AndAlso lookupResult.Extent.Kind = NamespaceKind.Compilation Then Dim ns = TryCast(symbol, NamespaceSymbol) If ns IsNot Nothing AndAlso ns.Extent.Kind <> NamespaceKind.Compilation AndAlso lookupResult.Extent.Compilation.GetCompilationNamespace(ns) Is lookupResult Then lookupResult = ns End If End If End If If lookupResult IsNot symbol Then ' Just the name alone didn't bind properly. Add our minimally qualified parent ' (if we have one), a dot, and then our name. Dim containingNamespace = symbol.ContainingNamespace If containingNamespace IsNot Nothing Then If containingNamespace.IsGlobalNamespace Then Debug.Assert(format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Included OrElse format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Omitted OrElse format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining) If format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Included Then AddGlobalNamespace(containingNamespace) AddOperator(SyntaxKind.DotToken) visitedParent = True End If Else VisitNamespace(containingNamespace, parentsEmittedName) AddOperator(SyntaxKind.DotToken) visitedParent = True End If End If End If builder.Add(CreatePart(SymbolDisplayPartKind.NamespaceName, symbol, emittedName, visitedParent)) End Sub Private Sub MinimallyQualify(symbol As INamedTypeSymbol) ' NOTE(cyrusn): We only call this once we've already checked if there is an alias or ' special type that corresponds to this type. ' ' We first start by trying to bind just our name and type arguments. If they bind to the ' symbol that we were constructed from. Otherwise, we get the minimal name of our ' parent, add a dot, and then add ourselves. Dim visitedParents As Boolean = False If Not (symbol.IsAnonymousType OrElse symbol.IsTupleType) Then If Not NameBoundSuccessfullyToSameSymbol(symbol) Then If IncludeNamedType(symbol.ContainingType) Then symbol.ContainingType.Accept(NotFirstVisitor) AddOperator(SyntaxKind.DotToken) ElseIf symbol.ContainingNamespace IsNot Nothing Then If symbol.ContainingNamespace.IsGlobalNamespace Then ' Error symbols are put into the global namespace if the compiler has no ' better guess for it, so we shouldn't go spitting it everywhere. If symbol.TypeKind <> TypeKind.Error Then AddKeyword(SyntaxKind.GlobalKeyword) AddOperator(SyntaxKind.DotToken) End If Else symbol.ContainingNamespace.Accept(NotFirstVisitor) AddOperator(SyntaxKind.DotToken) End If End If visitedParents = True End If End If AddNameAndTypeArgumentsOrParameters(symbol, visitedParents) End Sub Private Function TryAddAlias( symbol As INamespaceOrTypeSymbol, builder As ArrayBuilder(Of SymbolDisplayPart)) As Boolean Dim [alias] = GetAliasSymbol(symbol) If Not [alias] Is Nothing Then ' We must verify that the alias actually binds back to the thing it's aliasing. It's ' possible there's another symbol with the same name as the alias that binds first Dim aliasName = [alias].Name Dim boundSymbols = semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name:=aliasName) If boundSymbols.Length = 1 Then Dim boundAlias = TryCast(boundSymbols(0), IAliasSymbol) If boundAlias IsNot Nothing AndAlso boundAlias.Target.Equals(symbol) Then builder.Add(CreatePart(SymbolDisplayPartKind.AliasName, [alias], aliasName, False)) Return True End If End If End If Return False End Function Private Function GetAliasSymbol(symbol As INamespaceOrTypeSymbol) As IAliasSymbol If Not Me.IsMinimizing Then Return Nothing End If Dim token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt) Dim startNode = token.Parent ' NOTE(cyrusn): If we're in an imports clause, we can't use aliases. Dim clause = startNode.AncestorsAndSelf().OfType(Of ImportsClauseSyntax).FirstOrDefault() If clause IsNot Nothing Then Return Nothing End If Dim compilation = semanticModelOpt.Compilation Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim sourceFile = sourceModule.TryGetSourceFile(DirectCast(GetSyntaxTree(DirectCast(semanticModelOpt, SemanticModel)), VisualBasicSyntaxTree)) Debug.Assert(sourceFile IsNot Nothing) If Not sourceFile.AliasImportsOpt Is Nothing Then For Each [alias] In sourceFile.AliasImportsOpt.Values If [alias].Alias.Target = DirectCast(symbol, NamespaceOrTypeSymbol) Then Return [alias].Alias End If Next End If Return Nothing End Function Private Function GetSyntaxTree(semanticModel As SemanticModel) As SyntaxTree If Not semanticModel.IsSpeculativeSemanticModel Then Return semanticModel.SyntaxTree End If Debug.Assert(semanticModel.ParentModel IsNot Nothing) Debug.Assert(Not semanticModel.ParentModel.IsSpeculativeSemanticModel) Return semanticModel.ParentModel.SyntaxTree End Function Private Function RemoveAttributeSuffixIfNecessary(symbol As INamedTypeSymbol, symbolName As String) As String If format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix) AndAlso IsDerivedFromAttributeType(symbol) Then Dim nameWithoutAttributeSuffix As String = Nothing If symbolName.TryGetWithoutAttributeSuffix(False, nameWithoutAttributeSuffix) Then Dim token = SyntaxFactory.ParseToken(nameWithoutAttributeSuffix) If token.Kind = SyntaxKind.IdentifierToken Then symbolName = nameWithoutAttributeSuffix End If End If End If Return symbolName End Function Private Function IsDerivedFromAttributeType(ByVal derivedType As INamedTypeSymbol) As Boolean Return semanticModelOpt IsNot Nothing AndAlso DirectCast(derivedType, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, DirectCast(semanticModelOpt.Compilation, VisualBasicCompilation), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) 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.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class SymbolDisplayVisitor Protected Overrides Function ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes() As Boolean Dim token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt) Dim startNode = token.Parent Return SyntaxFacts.IsInNamespaceOrTypeContext(TryCast(startNode, ExpressionSyntax)) OrElse Me.inNamespaceOrType End Function Private Sub MinimallyQualify(symbol As INamespaceSymbol, emittedName As String, parentsEmittedName As String) Debug.Assert(symbol.ContainingNamespace IsNot Nothing OrElse symbol.IsGlobalNamespace) ' NOTE(cyrusn): We only call this once we've already checked if there is an alias that ' corresponds to this namespace. If symbol.IsGlobalNamespace Then ' nothing to add for global namespace itself Return End If Dim visitedParent = False ' Check if the name of this namespace binds to the same namespace symbol. If so, ' then that's all we need to add. Otherwise, we will add the minimally qualified ' version of our parent, and then add ourselves to that. Dim symbols = If( ShouldRestrictMinimallyQualifyLookupToNamespacesAndTypes(), semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name:=symbol.Name), semanticModelOpt.LookupSymbols(positionOpt, name:=symbol.Name)) Dim lookupResult As NamespaceSymbol = Nothing If symbols.Length = 1 Then lookupResult = TryCast(symbols(0), NamespaceSymbol) End If ' It is possible to get NamespaceSymbol with compilation extent here. ' Let's check this case. If lookupResult IsNot Nothing Then Debug.Assert(lookupResult.Extent.Kind = NamespaceKind.Module OrElse lookupResult.Extent.Kind = NamespaceKind.Compilation) If lookupResult IsNot symbol AndAlso lookupResult.Extent.Kind = NamespaceKind.Compilation Then Dim ns = TryCast(symbol, NamespaceSymbol) If ns IsNot Nothing AndAlso ns.Extent.Kind <> NamespaceKind.Compilation AndAlso lookupResult.Extent.Compilation.GetCompilationNamespace(ns) Is lookupResult Then lookupResult = ns End If End If End If If lookupResult IsNot symbol Then ' Just the name alone didn't bind properly. Add our minimally qualified parent ' (if we have one), a dot, and then our name. Dim containingNamespace = symbol.ContainingNamespace If containingNamespace IsNot Nothing Then If containingNamespace.IsGlobalNamespace Then Debug.Assert(format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Included OrElse format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Omitted OrElse format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining) If format.GlobalNamespaceStyle = SymbolDisplayGlobalNamespaceStyle.Included Then AddGlobalNamespace(containingNamespace) AddOperator(SyntaxKind.DotToken) visitedParent = True End If Else VisitNamespace(containingNamespace, parentsEmittedName) AddOperator(SyntaxKind.DotToken) visitedParent = True End If End If End If builder.Add(CreatePart(SymbolDisplayPartKind.NamespaceName, symbol, emittedName, visitedParent)) End Sub Private Sub MinimallyQualify(symbol As INamedTypeSymbol) ' NOTE(cyrusn): We only call this once we've already checked if there is an alias or ' special type that corresponds to this type. ' ' We first start by trying to bind just our name and type arguments. If they bind to the ' symbol that we were constructed from. Otherwise, we get the minimal name of our ' parent, add a dot, and then add ourselves. Dim visitedParents As Boolean = False If Not (symbol.IsAnonymousType OrElse symbol.IsTupleType) Then If Not NameBoundSuccessfullyToSameSymbol(symbol) Then If IncludeNamedType(symbol.ContainingType) Then symbol.ContainingType.Accept(NotFirstVisitor) AddOperator(SyntaxKind.DotToken) ElseIf symbol.ContainingNamespace IsNot Nothing Then If symbol.ContainingNamespace.IsGlobalNamespace Then ' Error symbols are put into the global namespace if the compiler has no ' better guess for it, so we shouldn't go spitting it everywhere. If symbol.TypeKind <> TypeKind.Error Then AddKeyword(SyntaxKind.GlobalKeyword) AddOperator(SyntaxKind.DotToken) End If Else symbol.ContainingNamespace.Accept(NotFirstVisitor) AddOperator(SyntaxKind.DotToken) End If End If visitedParents = True End If End If AddNameAndTypeArgumentsOrParameters(symbol, visitedParents) End Sub Private Function TryAddAlias( symbol As INamespaceOrTypeSymbol, builder As ArrayBuilder(Of SymbolDisplayPart)) As Boolean Dim [alias] = GetAliasSymbol(symbol) If Not [alias] Is Nothing Then ' We must verify that the alias actually binds back to the thing it's aliasing. It's ' possible there's another symbol with the same name as the alias that binds first Dim aliasName = [alias].Name Dim boundSymbols = semanticModelOpt.LookupNamespacesAndTypes(positionOpt, name:=aliasName) If boundSymbols.Length = 1 Then Dim boundAlias = TryCast(boundSymbols(0), IAliasSymbol) If boundAlias IsNot Nothing AndAlso boundAlias.Target.Equals(symbol) Then builder.Add(CreatePart(SymbolDisplayPartKind.AliasName, [alias], aliasName, False)) Return True End If End If End If Return False End Function Private Function GetAliasSymbol(symbol As INamespaceOrTypeSymbol) As IAliasSymbol If Not Me.IsMinimizing Then Return Nothing End If Dim token = semanticModelOpt.SyntaxTree.GetRoot().FindToken(positionOpt) Dim startNode = token.Parent ' NOTE(cyrusn): If we're in an imports clause, we can't use aliases. Dim clause = startNode.AncestorsAndSelf().OfType(Of ImportsClauseSyntax).FirstOrDefault() If clause IsNot Nothing Then Return Nothing End If Dim compilation = semanticModelOpt.Compilation Dim sourceModule = DirectCast(compilation.SourceModule, SourceModuleSymbol) Dim sourceFile = sourceModule.TryGetSourceFile(DirectCast(GetSyntaxTree(DirectCast(semanticModelOpt, SemanticModel)), VisualBasicSyntaxTree)) Debug.Assert(sourceFile IsNot Nothing) If Not sourceFile.AliasImportsOpt Is Nothing Then For Each [alias] In sourceFile.AliasImportsOpt.Values If [alias].Alias.Target = DirectCast(symbol, NamespaceOrTypeSymbol) Then Return [alias].Alias End If Next End If Return Nothing End Function Private Function GetSyntaxTree(semanticModel As SemanticModel) As SyntaxTree If Not semanticModel.IsSpeculativeSemanticModel Then Return semanticModel.SyntaxTree End If Debug.Assert(semanticModel.ParentModel IsNot Nothing) Debug.Assert(Not semanticModel.ParentModel.IsSpeculativeSemanticModel) Return semanticModel.ParentModel.SyntaxTree End Function Private Function RemoveAttributeSuffixIfNecessary(symbol As INamedTypeSymbol, symbolName As String) As String If format.MiscellaneousOptions.IncludesOption(SymbolDisplayMiscellaneousOptions.RemoveAttributeSuffix) AndAlso IsDerivedFromAttributeType(symbol) Then Dim nameWithoutAttributeSuffix As String = Nothing If symbolName.TryGetWithoutAttributeSuffix(False, nameWithoutAttributeSuffix) Then Dim token = SyntaxFactory.ParseToken(nameWithoutAttributeSuffix) If token.Kind = SyntaxKind.IdentifierToken Then symbolName = nameWithoutAttributeSuffix End If End If End If Return symbolName End Function Private Function IsDerivedFromAttributeType(ByVal derivedType As INamedTypeSymbol) As Boolean Return semanticModelOpt IsNot Nothing AndAlso DirectCast(derivedType, NamedTypeSymbol).IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, DirectCast(semanticModelOpt.Compilation, VisualBasicCompilation), useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) End Function End Class End Namespace
-1
dotnet/roslyn
56,135
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-09-02T21:01:14Z"
"2021-09-02T21:01:27Z"
99014d0615bf706b51c9e0aa325fc431a7d68711
7d328caf396488de8fc8a0ea4e39ae2e5824a48a
Merge release/dev17.0 to main. This is an automatically generated pull request from release/dev17.0 into main. Once all conflicts are resolved and all the tests pass, you are free to merge the pull request. 🐯 ## Troubleshooting conflicts ### Identify authors of changes which introduced merge conflicts Scroll to the bottom, then for each file containing conflicts copy its path into the following searches: - https://github.com/dotnet/roslyn/find/release/dev17.0 - https://github.com/dotnet/roslyn/find/main Usually the most recent change to a file between the two branches is considered to have introduced the conflicts, but sometimes it will be necessary to look for the conflicting lines and check the blame in each branch. Generally the author whose change introduced the conflicts should pull down this PR, fix the conflicts locally, then push up a commit resolving the conflicts. ### Resolve merge conflicts using your local repo Sometimes merge conflicts may be present on GitHub but merging locally will work without conflicts. This is due to differences between the merge algorithm used in local git versus the one used by GitHub. ``` bash git fetch --all git checkout merges/release/dev17.0-to-main git reset --hard upstream/main git merge upstream/release/dev17.0 # Fix merge conflicts git commit git push upstream merges/release/dev17.0-to-main --force ```
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.Templates.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeSynthesizedDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } private SynthesizedDelegateValue CreatePlaceholderSynthesizedDelegateValue(string name, RefKindVector refKinds, bool returnsVoid, int parameterCount) { var symbol = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, out _), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return new SynthesizedDelegateValue(this, symbol); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); // Ensure all previous synthesized delegates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousSynthesizedDelegates()) { if (GeneratedNames.TryParseSynthesizedDelegateName(key.Name, out var refKinds, out var returnsVoid, out var generation, out var parameterCount)) { var delegateKey = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); this.SynthesizedDelegates.GetOrAdd(delegateKey, (k, args) => CreatePlaceholderSynthesizedDelegateValue(key.Name, args.refKinds, args.returnsVoid, args.parameterCount), (refKinds, returnsVoid, parameterCount)); } } var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue> GetSynthesizedDelegates() { var result = new Dictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue>(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var delegateSymbol in synthesizedDelegates) { var key = new CodeAnalysis.Emit.SynthesizedDelegateKey(delegateSymbol.MetadataName); var value = new CodeAnalysis.Emit.SynthesizedDelegateValue(delegateSymbol.GetCciAdapter()); result.Add(key, value); } synthesizedDelegates.Free(); return result; } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created on module level. All requests for anonymous type symbols /// go via the instance of this class, the symbol will be either created or returned from cache. /// </summary> internal sealed partial class AnonymousTypeManager { /// <summary> /// Cache of created anonymous type templates used as an implementation of anonymous /// types in emit phase. /// </summary> private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> _lazyAnonymousTypeTemplates; /// <summary> /// Maps delegate signature shape (number of parameters and their ref-ness) to a synthesized generic delegate symbol. /// Unlike anonymous types synthesized delegates are not available through symbol APIs. They are only used in lowered bound trees. /// Currently used for dynamic call-site sites whose signature doesn't match any of the well-known Func or Action types. /// </summary> private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> _lazySynthesizedDelegates; private struct SynthesizedDelegateKey : IEquatable<SynthesizedDelegateKey> { private readonly RefKindVector _byRefs; private readonly ushort _parameterCount; private readonly bool _returnsVoid; private readonly int _generation; public SynthesizedDelegateKey(int parameterCount, RefKindVector byRefs, bool returnsVoid, int generation) { _parameterCount = (ushort)parameterCount; _returnsVoid = returnsVoid; _generation = generation; _byRefs = byRefs; } public string MakeTypeName() { return GeneratedNames.MakeSynthesizedDelegateName(_byRefs, _returnsVoid, _generation); } public override bool Equals(object obj) { return obj is SynthesizedDelegateKey && Equals((SynthesizedDelegateKey)obj); } public bool Equals(SynthesizedDelegateKey other) { return _parameterCount == other._parameterCount && _returnsVoid == other._returnsVoid && _generation == other._generation && _byRefs.Equals(other._byRefs); } public override int GetHashCode() { return Hash.Combine( Hash.Combine((int)_parameterCount, _generation), Hash.Combine(_returnsVoid.GetHashCode(), _byRefs.GetHashCode())); } } private struct SynthesizedDelegateValue { public readonly SynthesizedDelegateSymbol Delegate; // the manager that created this delegate: public readonly AnonymousTypeManager Manager; public SynthesizedDelegateValue(AnonymousTypeManager manager, SynthesizedDelegateSymbol @delegate) { Debug.Assert(manager != null && (object)@delegate != null); this.Manager = manager; this.Delegate = @delegate; } } #if DEBUG /// <summary> /// Holds a collection of all the locations of anonymous types and delegates from source /// </summary> private readonly ConcurrentDictionary<Location, bool> _sourceLocationsSeen = new ConcurrentDictionary<Location, bool>(); #endif [Conditional("DEBUG")] private void CheckSourceLocationSeen(AnonymousTypePublicSymbol anonymous) { #if DEBUG Location location = anonymous.Locations[0]; if (location.IsInSource) { if (this.AreTemplatesSealed) { Debug.Assert(_sourceLocationsSeen.ContainsKey(location)); } else { _sourceLocationsSeen.TryAdd(location, true); } } #endif } private ConcurrentDictionary<string, AnonymousTypeTemplateSymbol> AnonymousTypeTemplates { get { // Lazily create a template types cache if (_lazyAnonymousTypeTemplates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager.AnonymousTypeTemplates; Interlocked.CompareExchange(ref _lazyAnonymousTypeTemplates, previousCache == null ? new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>() : new ConcurrentDictionary<string, AnonymousTypeTemplateSymbol>(previousCache), null); } return _lazyAnonymousTypeTemplates; } } private ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue> SynthesizedDelegates { get { if (_lazySynthesizedDelegates == null) { CSharpCompilation previousSubmission = this.Compilation.PreviousSubmission; // TODO (tomat): avoid recursion var previousCache = (previousSubmission == null) ? null : previousSubmission.AnonymousTypeManager._lazySynthesizedDelegates; Interlocked.CompareExchange(ref _lazySynthesizedDelegates, previousCache == null ? new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>() : new ConcurrentDictionary<SynthesizedDelegateKey, SynthesizedDelegateValue>(previousCache), null); } return _lazySynthesizedDelegates; } } internal SynthesizedDelegateSymbol SynthesizeDelegate(int parameterCount, RefKindVector refKinds, bool returnsVoid, int generation) { // parameterCount doesn't include return type Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (returnsVoid ? 0 : 1)); var key = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); SynthesizedDelegateValue result; if (this.SynthesizedDelegates.TryGetValue(key, out result)) { return result.Delegate; } // NOTE: the newly created template may be thrown away if another thread wins var synthesizedDelegate = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, key.MakeTypeName(), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return this.SynthesizedDelegates.GetOrAdd(key, new SynthesizedDelegateValue(this, synthesizedDelegate)).Delegate; } /// <summary> /// Given anonymous type provided constructs an implementation type symbol to be used in emit phase; /// if the anonymous type has at least one field the implementation type symbol will be created based on /// a generic type template generated for each 'unique' anonymous type structure, otherwise the template /// type will be non-generic. /// </summary> private NamedTypeSymbol ConstructAnonymousTypeImplementationSymbol(AnonymousTypePublicSymbol anonymous) { Debug.Assert(ReferenceEquals(this, anonymous.Manager)); CheckSourceLocationSeen(anonymous); AnonymousTypeDescriptor typeDescr = anonymous.TypeDescriptor; typeDescr.AssertIsGood(); // Get anonymous type template AnonymousTypeTemplateSymbol template; if (!this.AnonymousTypeTemplates.TryGetValue(typeDescr.Key, out template)) { // NOTE: the newly created template may be thrown away if another thread wins template = this.AnonymousTypeTemplates.GetOrAdd(typeDescr.Key, new AnonymousTypeTemplateSymbol(this, typeDescr)); } // Adjust template location if the template is owned by this manager if (ReferenceEquals(template.Manager, this)) { template.AdjustLocation(typeDescr.Location); } // In case template is not generic, just return it if (template.Arity == 0) { return template; } // otherwise construct type using the field types var typeArguments = typeDescr.Fields.SelectAsArray(f => f.Type); return template.Construct(typeArguments); } private AnonymousTypeTemplateSymbol CreatePlaceholderTemplate(Microsoft.CodeAnalysis.Emit.AnonymousTypeKey key) { var fields = key.Fields.SelectAsArray(f => new AnonymousTypeField(f.Name, Location.None, default)); var typeDescr = new AnonymousTypeDescriptor(fields, Location.None); return new AnonymousTypeTemplateSymbol(this, typeDescr); } private SynthesizedDelegateValue CreatePlaceholderSynthesizedDelegateValue(string name, RefKindVector refKinds, bool returnsVoid, int parameterCount) { var symbol = new SynthesizedDelegateSymbol( this.Compilation.Assembly.GlobalNamespace, MetadataHelpers.InferTypeArityAndUnmangleMetadataName(name, out _), this.System_Object, Compilation.GetSpecialType(SpecialType.System_IntPtr), returnsVoid ? Compilation.GetSpecialType(SpecialType.System_Void) : null, parameterCount, refKinds); return new SynthesizedDelegateValue(this, symbol); } /// <summary> /// Resets numbering in anonymous type names and compiles the /// anonymous type methods. Also seals the collection of templates. /// </summary> public void AssignTemplatesNamesAndCompile(MethodCompiler compiler, PEModuleBuilder moduleBeingBuilt, BindingDiagnosticBag diagnostics) { // Ensure all previous anonymous type templates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousAnonymousTypes()) { var templateKey = AnonymousTypeDescriptor.ComputeKey(key.Fields, f => f.Name); this.AnonymousTypeTemplates.GetOrAdd(templateKey, k => this.CreatePlaceholderTemplate(key)); } // Get all anonymous types owned by this manager var builder = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(builder); // If the collection is not sealed yet we should assign // new indexes to the created anonymous type templates if (!this.AreTemplatesSealed) { // If we are emitting .NET module, include module's name into type's name to ensure // uniqueness across added modules. string moduleId; if (moduleBeingBuilt.OutputKind == OutputKind.NetModule) { moduleId = moduleBeingBuilt.Name; string extension = OutputKind.NetModule.GetDefaultExtension(); if (moduleId.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { moduleId = moduleId.Substring(0, moduleId.Length - extension.Length); } moduleId = MetadataHelpers.MangleForTypeNameIfNeeded(moduleId); } else { moduleId = string.Empty; } int nextIndex = moduleBeingBuilt.GetNextAnonymousTypeIndex(); foreach (var template in builder) { string name; int index; if (!moduleBeingBuilt.TryGetAnonymousTypeName(template, out name, out index)) { index = nextIndex++; name = GeneratedNames.MakeAnonymousTypeTemplateName(index, this.Compilation.GetSubmissionSlotIndex(), moduleId); } // normally it should only happen once, but in case there is a race // NameAndIndex.set has an assert which guarantees that the // template name provided is the same as the one already assigned template.NameAndIndex = new NameAndIndex(name, index); } this.SealTemplates(); } if (builder.Count > 0 && !ReportMissingOrErroneousSymbols(diagnostics)) { // Process all the templates foreach (var template in builder) { foreach (var method in template.SpecialMembers) { moduleBeingBuilt.AddSynthesizedDefinition(template, method.GetCciAdapter()); } compiler.Visit(template, null); } } builder.Free(); // Ensure all previous synthesized delegates are included so the // types are available for subsequent edit and continue generations. foreach (var key in moduleBeingBuilt.GetPreviousSynthesizedDelegates()) { if (GeneratedNames.TryParseSynthesizedDelegateName(key.Name, out var refKinds, out var returnsVoid, out var generation, out var parameterCount)) { var delegateKey = new SynthesizedDelegateKey(parameterCount, refKinds, returnsVoid, generation); this.SynthesizedDelegates.GetOrAdd(delegateKey, (k, args) => CreatePlaceholderSynthesizedDelegateValue(key.Name, args.refKinds, args.returnsVoid, args.parameterCount), (refKinds, returnsVoid, parameterCount)); } } var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var synthesizedDelegate in synthesizedDelegates) { compiler.Visit(synthesizedDelegate, null); } synthesizedDelegates.Free(); } /// <summary> /// The set of anonymous type templates created by /// this AnonymousTypeManager, in fixed order. /// </summary> private void GetCreatedAnonymousTypeTemplates(ArrayBuilder<AnonymousTypeTemplateSymbol> builder) { Debug.Assert(!builder.Any()); var anonymousTypes = _lazyAnonymousTypeTemplates; if (anonymousTypes != null) { foreach (var template in anonymousTypes.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template); } } // Sort type templates using smallest location builder.Sort(new AnonymousTypeComparer(this.Compilation)); } } /// <summary> /// The set of synthesized delegates created by /// this AnonymousTypeManager. /// </summary> private void GetCreatedSynthesizedDelegates(ArrayBuilder<SynthesizedDelegateSymbol> builder) { Debug.Assert(!builder.Any()); var delegates = _lazySynthesizedDelegates; if (delegates != null) { foreach (var template in delegates.Values) { if (ReferenceEquals(template.Manager, this)) { builder.Add(template.Delegate); } } builder.Sort(SynthesizedDelegateSymbolComparer.Instance); } } private class SynthesizedDelegateSymbolComparer : IComparer<SynthesizedDelegateSymbol> { public static readonly SynthesizedDelegateSymbolComparer Instance = new SynthesizedDelegateSymbolComparer(); public int Compare(SynthesizedDelegateSymbol x, SynthesizedDelegateSymbol y) { return x.MetadataName.CompareTo(y.MetadataName); } } internal IReadOnlyDictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue> GetSynthesizedDelegates() { var result = new Dictionary<CodeAnalysis.Emit.SynthesizedDelegateKey, CodeAnalysis.Emit.SynthesizedDelegateValue>(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); foreach (var delegateSymbol in synthesizedDelegates) { var key = new CodeAnalysis.Emit.SynthesizedDelegateKey(delegateSymbol.MetadataName); var value = new CodeAnalysis.Emit.SynthesizedDelegateValue(delegateSymbol.GetCciAdapter()); result.Add(key, value); } synthesizedDelegates.Free(); return result; } internal IReadOnlyDictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue> GetAnonymousTypeMap() { var result = new Dictionary<Microsoft.CodeAnalysis.Emit.AnonymousTypeKey, Microsoft.CodeAnalysis.Emit.AnonymousTypeValue>(); var templates = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); // Get anonymous types but not synthesized delegates. (Delegate types are // not reused across generations since reuse would add complexity (such // as parsing delegate type names from metadata) without a clear benefit.) GetCreatedAnonymousTypeTemplates(templates); foreach (var template in templates) { var nameAndIndex = template.NameAndIndex; var key = template.GetAnonymousTypeKey(); var value = new Microsoft.CodeAnalysis.Emit.AnonymousTypeValue(nameAndIndex.Name, nameAndIndex.Index, template.GetCciAdapter()); result.Add(key, value); } templates.Free(); return result; } /// <summary> /// Returns all templates owned by this type manager /// </summary> internal ImmutableArray<NamedTypeSymbol> GetAllCreatedTemplates() { // NOTE: templates may not be sealed in case metadata is being emitted without IL var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var anonymousTypes = ArrayBuilder<AnonymousTypeTemplateSymbol>.GetInstance(); GetCreatedAnonymousTypeTemplates(anonymousTypes); builder.AddRange(anonymousTypes); anonymousTypes.Free(); var synthesizedDelegates = ArrayBuilder<SynthesizedDelegateSymbol>.GetInstance(); GetCreatedSynthesizedDelegates(synthesizedDelegates); builder.AddRange(synthesizedDelegates); synthesizedDelegates.Free(); return builder.ToImmutableAndFree(); } /// <summary> /// Returns true if the named type is an implementation template for an anonymous type /// </summary> internal static bool IsAnonymousTypeTemplate(NamedTypeSymbol type) { return type is AnonymousTypeTemplateSymbol; } /// <summary> /// Retrieves methods of anonymous type template which are not placed to symbol table. /// In current implementation those are overridden 'ToString', 'Equals' and 'GetHashCode' /// </summary> internal static ImmutableArray<MethodSymbol> GetAnonymousTypeHiddenMethods(NamedTypeSymbol type) { Debug.Assert((object)type != null); return ((AnonymousTypeTemplateSymbol)type).SpecialMembers; } /// <summary> /// Translates anonymous type public symbol into an implementation type symbol to be used in emit. /// </summary> internal static NamedTypeSymbol TranslateAnonymousTypeSymbol(NamedTypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeImplementationSymbol(anonymous); } /// <summary> /// Translates anonymous type method symbol into an implementation method symbol to be used in emit. /// </summary> internal static MethodSymbol TranslateAnonymousTypeMethodSymbol(MethodSymbol method) { Debug.Assert((object)method != null); NamedTypeSymbol translatedType = TranslateAnonymousTypeSymbol(method.ContainingType); // find a method in anonymous type template by name foreach (var member in ((NamedTypeSymbol)translatedType.OriginalDefinition).GetMembers(method.Name)) { if (member.Kind == SymbolKind.Method) { // found a method definition, get a constructed method return ((MethodSymbol)member).AsMember(translatedType); } } throw ExceptionUtilities.Unreachable; } /// <summary> /// Comparator being used for stable ordering in anonymous type indices. /// </summary> private sealed class AnonymousTypeComparer : IComparer<AnonymousTypeTemplateSymbol> { private readonly CSharpCompilation _compilation; public AnonymousTypeComparer(CSharpCompilation compilation) { _compilation = compilation; } public int Compare(AnonymousTypeTemplateSymbol x, AnonymousTypeTemplateSymbol y) { if ((object)x == (object)y) { return 0; } // We compare two anonymous type templated by comparing their locations and descriptor keys // NOTE: If anonymous type got to this phase it must have the location set int result = this.CompareLocations(x.SmallestLocation, y.SmallestLocation); if (result == 0) { // It is still possible for two templates to have the same smallest location // in case they are implicitly created and use the same syntax for location result = string.CompareOrdinal(x.TypeDescriptorKey, y.TypeDescriptorKey); } return result; } private int CompareLocations(Location x, Location y) { if (x == y) { return 0; } else if (x == Location.None) { return -1; } else if (y == Location.None) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Test2/Compilation/CompilationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests <[UseExportProvider]> Public Class CompilationTests Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName) End Function <Fact> <WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")> Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task Dim workspaceDefinition = <Workspace> <Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true"> <Document> var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations </Document> </Project> </Workspace> Dim composition = EditorTestCompositions.EditorFeatures.AddParts( GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition) Dim project = GetProject(workspace.CurrentSolution, "TestAssembly") Assert.Null(Await project.GetCompilationAsync()) Assert.Null(Await project.GetCompilationAsync()) Assert.False(Await project.ContainsSymbolsWithNameAsync(Function(dummy) True, SymbolFilter.TypeAndMember, CancellationToken.None)) Assert.Empty(Await project.GetDocumentsWithNameAsync(Function(dummy) True, SymbolFilter.TypeAndMember, CancellationToken.None)) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.Implementation.Compilation.UnitTests <[UseExportProvider]> Public Class CompilationTests Private Shared Function GetProject(snapshot As Solution, assemblyName As String) As Project Return snapshot.Projects.Single(Function(p) p.AssemblyName = assemblyName) End Function <Fact> <WorkItem(1107492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107492")> Public Async Function TestProjectThatDoesntSupportCompilations() As Tasks.Task Dim workspaceDefinition = <Workspace> <Project Language="NoCompilation" AssemblyName="TestAssembly" CommonReferencesPortable="true"> <Document> var x = {}; // e.g., TypeScript code or anything else that doesn't support compilations </Document> </Project> </Workspace> Dim composition = EditorTestCompositions.EditorFeatures.AddParts( GetType(NoCompilationContentTypeLanguageService), GetType(NoCompilationContentTypeDefinitions)) Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=composition) Dim project = GetProject(workspace.CurrentSolution, "TestAssembly") Assert.Null(Await project.GetCompilationAsync()) Assert.Null(Await project.GetCompilationAsync()) Assert.False(Await project.ContainsSymbolsWithNameAsync(Function(dummy) True, SymbolFilter.TypeAndMember, CancellationToken.None)) End Using End Function End Class End Namespace
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Solution/Project.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a project that is part of a <see cref="Solution"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Project { private readonly Solution _solution; private readonly ProjectState _projectState; private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty; private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty; private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty; private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty; internal Project(Solution solution, ProjectState projectState) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(projectState); _solution = solution; _projectState = projectState; } internal ProjectState State => _projectState; /// <summary> /// The solution this project is part of. /// </summary> public Solution Solution => _solution; /// <summary> /// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only /// one project may have this ID in any given solution. /// </summary> public ProjectId Id => _projectState.Id; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => _projectState.FilePath; /// <summary> /// The path to the output file, or null if it is not known. /// </summary> public string? OutputFilePath => _projectState.OutputFilePath; /// <summary> /// The path to the reference assembly output file, or null if it is not known. /// </summary> public string? OutputRefFilePath => _projectState.OutputRefFilePath; /// <summary> /// Compilation output file paths. /// </summary> public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various feature can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> public string? DefaultNamespace => _projectState.DefaultNamespace; /// <summary> /// <see langword="true"/> if this <see cref="Project"/> supports providing data through the /// <see cref="GetCompilationAsync(CancellationToken)"/> method. /// /// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead. /// </summary> public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; /// <summary> /// The language services from the host environment associated with this project's language. /// </summary> public HostLanguageServices LanguageServices => _projectState.LanguageServices; /// <summary> /// The language associated with the project. /// </summary> public string Language => _projectState.Language; /// <summary> /// The name of the assembly this project represents. /// </summary> public string AssemblyName => _projectState.AssemblyName; /// <summary> /// The name of the project. This may be different than the assembly name. /// </summary> public string Name => _projectState.Name; /// <summary> /// The list of all other metadata sources (assemblies) that this project references. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences; /// <summary> /// The list of all other projects within the same solution that this project references. /// </summary> public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId)); /// <summary> /// The list of all other projects that this project references, including projects that /// are not part of the solution. /// </summary> public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences; /// <summary> /// The list of all the diagnostic analyzer references for this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences; /// <summary> /// The options used by analyzers for this project. /// </summary> public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions; /// <summary> /// The options used when building the compilation for this project. /// </summary> public CompilationOptions? CompilationOptions => _projectState.CompilationOptions; /// <summary> /// The options used when parsing documents for this project. /// </summary> public ParseOptions? ParseOptions => _projectState.ParseOptions; /// <summary> /// Returns true if this is a submission project. /// </summary> public bool IsSubmission => _projectState.IsSubmission; /// <summary> /// True if the project has any documents. /// </summary> public bool HasDocuments => !_projectState.DocumentStates.IsEmpty; /// <summary> /// All the document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids; /// <summary> /// All the regular documents associated with this project. Documents produced from source generators are returned by /// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>. /// </summary> public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!; /// <summary> /// All the additional documents associated with this project. /// </summary> public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!; /// <summary> /// All the <see cref="AnalyzerConfigDocument"/>s associated with this project. /// </summary> public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!; /// <summary> /// True if the project contains a document with the specified ID. /// </summary> public bool ContainsDocument(DocumentId documentId) => _projectState.DocumentStates.Contains(documentId); /// <summary> /// True if the project contains an additional document with the specified ID. /// </summary> public bool ContainsAdditionalDocument(DocumentId documentId) => _projectState.AdditionalDocumentStates.Contains(documentId); /// <summary> /// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID. /// </summary> public bool ContainsAnalyzerConfigDocument(DocumentId documentId) => _projectState.AnalyzerConfigDocumentStates.Contains(documentId); /// <summary> /// Get the documentId in this project with the specified syntax tree. /// </summary> public DocumentId? GetDocumentId(SyntaxTree? syntaxTree) => _solution.GetDocumentId(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified syntax tree. /// </summary> public Document? GetDocument(SyntaxTree? syntaxTree) => _solution.GetDocument(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified document Id. /// </summary> public Document? GetDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this); /// <summary> /// Get the additional document in this project with the specified document Id. /// </summary> public TextDocument? GetAdditionalDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this); /// <summary> /// Get the analyzer config document in this project with the specified document Id. /// </summary> public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this); /// <summary> /// Gets a document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var document = GetDocument(documentId); if (document != null || !includeSourceGenerated) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId); if (document != null) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all source generated documents in this project. /// </summary> public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); // return an iterator to avoid eagerly allocating all the document instances return generatedDocumentStates.States.Values.Select(state => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!; } internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false)); } public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { // Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument)) { return sourceGeneratedDocument; } // We'll have to run generators if we haven't already and now try to find it. var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false); var generatedDocumentState = generatedDocumentStates.GetState(documentId); if (generatedDocumentState != null) { return GetOrCreateSourceGeneratedDocument(generatedDocumentState); } return null; } internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state) => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!; /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) { // Easy case: do we already have the SourceGeneratedDocument created? if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document)) { return document; } // Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go // try to fetch the state. var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (documentState == null) { return null; } return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this)); } internal async Task<bool> ContainsSymbolsWithNameAsync(string name, SymbolFilter filter, CancellationToken cancellationToken) { return this.SupportsCompilation && await _solution.State.ContainsSymbolsWithNameAsync(Id, name, filter, cancellationToken).ConfigureAwait(false); } internal async Task<bool> ContainsSymbolsWithNameAsync(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { return this.SupportsCompilation && await _solution.State.ContainsSymbolsWithNameAsync(Id, predicate, filter, cancellationToken).ConfigureAwait(false); } internal async Task<IEnumerable<Document>> GetDocumentsWithNameAsync(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) => (await _solution.State.GetDocumentsWithNameAsync(Id, predicate, filter, cancellationToken).ConfigureAwait(false)).Select(s => _solution.GetDocument(s.Id)!); private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction = (documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null; private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction = (documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null; private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction = (documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null; private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction = (documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state); /// <summary> /// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all /// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/> /// or create a new one otherwise. /// </summary> public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation) => _solution.State.TryGetCompilation(this.Id, out compilation); /// <summary> /// Get the <see cref="Compilation"/> for this project asynchronously. /// </summary> /// <returns> /// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see /// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default) => _solution.State.GetCompilationAsync(_projectState, cancellationToken); /// <summary> /// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects. /// </summary> // TODO: make this public internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default) => _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken); /// <summary> /// Gets an object that lists the added, changed and removed documents between this project and the specified project. /// </summary> public ProjectChanges GetChanges(Project oldProject) { if (oldProject == null) { throw new ArgumentNullException(nameof(oldProject)); } return new ProjectChanges(this, oldProject); } /// <summary> /// The project version. This equates to the version of the project file. /// </summary> public VersionStamp Version => _projectState.Version; /// <summary> /// The version of the most recently modified document. /// </summary> public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetLatestDocumentVersionAsync(cancellationToken); /// <summary> /// The most recent version of the project, its documents and all dependent projects and documents. /// </summary> public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project including the semantics of referenced projects. /// This version changes whenever the consumable declarations of this project and/or projects it depends on change. /// </summary> public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project not including the semantics of referenced projects. /// This version changes only when the consumable declarations of this project change. /// </summary> public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetSemanticVersionAsync(cancellationToken); /// <summary> /// Creates a new instance of this project updated to have the new assembly name. /// </summary> public Project WithAssemblyName(string assemblyName) => this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the new default namespace. /// </summary> public Project WithDefaultNamespace(string defaultNamespace) => this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified compilation options. /// </summary> public Project WithCompilationOptions(CompilationOptions options) => this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified parse options. /// </summary> public Project WithParseOptions(ParseOptions options) => this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project reference /// in addition to already existing ones. /// </summary> public Project AddProjectReference(ProjectReference projectReference) => this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project references /// in addition to already existing ones. /// </summary> public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified project reference. /// </summary> public Project RemoveProjectReference(ProjectReference projectReference) => this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing project references /// with the specified ones. /// </summary> public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata reference /// in addition to already existing ones. /// </summary> public Project AddMetadataReference(MetadataReference metadataReference) => this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata references /// in addition to already existing ones. /// </summary> public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) => this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing metadata reference /// with the specified ones. /// </summary> public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer reference /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer references /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) => this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer reference. /// </summary> public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing analyzer references /// with the specified ones. /// </summary> public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs) => this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!; /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); // use preserve identity for forked solution directly from syntax node. // this lets us not serialize temporary tree unnecessarily return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id, debugName: name); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new analyzer config document in a new instance of this project. /// </summary> public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified document. /// </summary> public Project RemoveDocument(DocumentId documentId) { // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified documents. /// </summary> public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional document. /// </summary> public Project RemoveAdditionalDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional documents. /// </summary> public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer config document. /// </summary> public Project RemoveAnalyzerConfigDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s. /// </summary> public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id); } private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds) { foreach (var documentId in documentIds) { // Dealing with nulls is handled by the caller of this if (documentId?.ProjectId != this.Id) { throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId)); } } } internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() => _projectState.GetAnalyzerConfigOptions(); private string GetDebuggerDisplay() => this.Name; internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache) => Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Host; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Collections.Immutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a project that is part of a <see cref="Solution"/>. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Project { private readonly Solution _solution; private readonly ProjectState _projectState; private ImmutableHashMap<DocumentId, Document> _idToDocumentMap = ImmutableHashMap<DocumentId, Document>.Empty; private ImmutableHashMap<DocumentId, SourceGeneratedDocument> _idToSourceGeneratedDocumentMap = ImmutableHashMap<DocumentId, SourceGeneratedDocument>.Empty; private ImmutableHashMap<DocumentId, AdditionalDocument> _idToAdditionalDocumentMap = ImmutableHashMap<DocumentId, AdditionalDocument>.Empty; private ImmutableHashMap<DocumentId, AnalyzerConfigDocument> _idToAnalyzerConfigDocumentMap = ImmutableHashMap<DocumentId, AnalyzerConfigDocument>.Empty; internal Project(Solution solution, ProjectState projectState) { Contract.ThrowIfNull(solution); Contract.ThrowIfNull(projectState); _solution = solution; _projectState = projectState; } internal ProjectState State => _projectState; /// <summary> /// The solution this project is part of. /// </summary> public Solution Solution => _solution; /// <summary> /// The ID of the project. Multiple <see cref="Project"/> instances may share the same ID. However, only /// one project may have this ID in any given solution. /// </summary> public ProjectId Id => _projectState.Id; /// <summary> /// The path to the project file or null if there is no project file. /// </summary> public string? FilePath => _projectState.FilePath; /// <summary> /// The path to the output file, or null if it is not known. /// </summary> public string? OutputFilePath => _projectState.OutputFilePath; /// <summary> /// The path to the reference assembly output file, or null if it is not known. /// </summary> public string? OutputRefFilePath => _projectState.OutputRefFilePath; /// <summary> /// Compilation output file paths. /// </summary> public CompilationOutputInfo CompilationOutputInfo => _projectState.CompilationOutputInfo; /// <summary> /// The default namespace of the project ("" if not defined, which means global namespace), /// or null if it is unknown or not applicable. /// </summary> /// <remarks> /// Right now VB doesn't have the concept of "default namespace". But we conjure one in workspace /// by assigning the value of the project's root namespace to it. So various feature can choose to /// use it for their own purpose. /// In the future, we might consider officially exposing "default namespace" for VB project /// (e.g. through a "defaultnamespace" msbuild property) /// </remarks> public string? DefaultNamespace => _projectState.DefaultNamespace; /// <summary> /// <see langword="true"/> if this <see cref="Project"/> supports providing data through the /// <see cref="GetCompilationAsync(CancellationToken)"/> method. /// /// If <see langword="false"/> then <see cref="GetCompilationAsync(CancellationToken)"/> method will return <see langword="null"/> instead. /// </summary> public bool SupportsCompilation => this.LanguageServices.GetService<ICompilationFactoryService>() != null; /// <summary> /// The language services from the host environment associated with this project's language. /// </summary> public HostLanguageServices LanguageServices => _projectState.LanguageServices; /// <summary> /// The language associated with the project. /// </summary> public string Language => _projectState.Language; /// <summary> /// The name of the assembly this project represents. /// </summary> public string AssemblyName => _projectState.AssemblyName; /// <summary> /// The name of the project. This may be different than the assembly name. /// </summary> public string Name => _projectState.Name; /// <summary> /// The list of all other metadata sources (assemblies) that this project references. /// </summary> public IReadOnlyList<MetadataReference> MetadataReferences => _projectState.MetadataReferences; /// <summary> /// The list of all other projects within the same solution that this project references. /// </summary> public IEnumerable<ProjectReference> ProjectReferences => _projectState.ProjectReferences.Where(pr => this.Solution.ContainsProject(pr.ProjectId)); /// <summary> /// The list of all other projects that this project references, including projects that /// are not part of the solution. /// </summary> public IReadOnlyList<ProjectReference> AllProjectReferences => _projectState.ProjectReferences; /// <summary> /// The list of all the diagnostic analyzer references for this project. /// </summary> public IReadOnlyList<AnalyzerReference> AnalyzerReferences => _projectState.AnalyzerReferences; /// <summary> /// The options used by analyzers for this project. /// </summary> public AnalyzerOptions AnalyzerOptions => _projectState.AnalyzerOptions; /// <summary> /// The options used when building the compilation for this project. /// </summary> public CompilationOptions? CompilationOptions => _projectState.CompilationOptions; /// <summary> /// The options used when parsing documents for this project. /// </summary> public ParseOptions? ParseOptions => _projectState.ParseOptions; /// <summary> /// Returns true if this is a submission project. /// </summary> public bool IsSubmission => _projectState.IsSubmission; /// <summary> /// True if the project has any documents. /// </summary> public bool HasDocuments => !_projectState.DocumentStates.IsEmpty; /// <summary> /// All the document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> DocumentIds => _projectState.DocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> public IReadOnlyList<DocumentId> AdditionalDocumentIds => _projectState.AdditionalDocumentStates.Ids; /// <summary> /// All the additional document IDs associated with this project. /// </summary> internal IReadOnlyList<DocumentId> AnalyzerConfigDocumentIds => _projectState.AnalyzerConfigDocumentStates.Ids; /// <summary> /// All the regular documents associated with this project. Documents produced from source generators are returned by /// <see cref="GetSourceGeneratedDocumentsAsync(CancellationToken)"/>. /// </summary> public IEnumerable<Document> Documents => DocumentIds.Select(GetDocument)!; /// <summary> /// All the additional documents associated with this project. /// </summary> public IEnumerable<TextDocument> AdditionalDocuments => AdditionalDocumentIds.Select(GetAdditionalDocument)!; /// <summary> /// All the <see cref="AnalyzerConfigDocument"/>s associated with this project. /// </summary> public IEnumerable<AnalyzerConfigDocument> AnalyzerConfigDocuments => AnalyzerConfigDocumentIds.Select(GetAnalyzerConfigDocument)!; /// <summary> /// True if the project contains a document with the specified ID. /// </summary> public bool ContainsDocument(DocumentId documentId) => _projectState.DocumentStates.Contains(documentId); /// <summary> /// True if the project contains an additional document with the specified ID. /// </summary> public bool ContainsAdditionalDocument(DocumentId documentId) => _projectState.AdditionalDocumentStates.Contains(documentId); /// <summary> /// True if the project contains an <see cref="AnalyzerConfigDocument"/> with the specified ID. /// </summary> public bool ContainsAnalyzerConfigDocument(DocumentId documentId) => _projectState.AnalyzerConfigDocumentStates.Contains(documentId); /// <summary> /// Get the documentId in this project with the specified syntax tree. /// </summary> public DocumentId? GetDocumentId(SyntaxTree? syntaxTree) => _solution.GetDocumentId(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified syntax tree. /// </summary> public Document? GetDocument(SyntaxTree? syntaxTree) => _solution.GetDocument(syntaxTree, this.Id); /// <summary> /// Get the document in this project with the specified document Id. /// </summary> public Document? GetDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToDocumentMap, documentId, s_tryCreateDocumentFunction, this); /// <summary> /// Get the additional document in this project with the specified document Id. /// </summary> public TextDocument? GetAdditionalDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAdditionalDocumentMap, documentId, s_tryCreateAdditionalDocumentFunction, this); /// <summary> /// Get the analyzer config document in this project with the specified document Id. /// </summary> public AnalyzerConfigDocument? GetAnalyzerConfigDocument(DocumentId documentId) => ImmutableHashMapExtensions.GetOrAdd(ref _idToAnalyzerConfigDocumentMap, documentId, s_tryCreateAnalyzerConfigDocumentFunction, this); /// <summary> /// Gets a document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<Document?> GetDocumentAsync(DocumentId documentId, bool includeSourceGenerated = false, CancellationToken cancellationToken = default) { var document = GetDocument(documentId); if (document != null || !includeSourceGenerated) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a document, additional document, analyzer config document or a source generated document in this solution with the specified document ID. /// </summary> internal async ValueTask<TextDocument?> GetTextDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { var document = GetDocument(documentId) ?? GetAdditionalDocument(documentId) ?? GetAnalyzerConfigDocument(documentId); if (document != null) { return document; } return await GetSourceGeneratedDocumentAsync(documentId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all source generated documents in this project. /// </summary> public async ValueTask<IEnumerable<SourceGeneratedDocument>> GetSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(this.State, cancellationToken).ConfigureAwait(false); // return an iterator to avoid eagerly allocating all the document instances return generatedDocumentStates.States.Values.Select(state => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this)))!; } internal async ValueTask<IEnumerable<Document>> GetAllRegularAndSourceGeneratedDocumentsAsync(CancellationToken cancellationToken = default) { return Documents.Concat(await GetSourceGeneratedDocumentsAsync(cancellationToken).ConfigureAwait(false)); } public async ValueTask<SourceGeneratedDocument?> GetSourceGeneratedDocumentAsync(DocumentId documentId, CancellationToken cancellationToken = default) { // Quick check first: if we already have created a SourceGeneratedDocument wrapper, we're good if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var sourceGeneratedDocument)) { return sourceGeneratedDocument; } // We'll have to run generators if we haven't already and now try to find it. var generatedDocumentStates = await _solution.State.GetSourceGeneratedDocumentStatesAsync(State, cancellationToken).ConfigureAwait(false); var generatedDocumentState = generatedDocumentStates.GetState(documentId); if (generatedDocumentState != null) { return GetOrCreateSourceGeneratedDocument(generatedDocumentState); } return null; } internal SourceGeneratedDocument GetOrCreateSourceGeneratedDocument(SourceGeneratedDocumentState state) => ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, state.Id, s_createSourceGeneratedDocumentFunction, (state, this))!; /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> internal SourceGeneratedDocument? TryGetSourceGeneratedDocumentForAlreadyGeneratedId(DocumentId documentId) { // Easy case: do we already have the SourceGeneratedDocument created? if (_idToSourceGeneratedDocumentMap.TryGetValue(documentId, out var document)) { return document; } // Trickier case now: it's possible we generated this, but we don't actually have the SourceGeneratedDocument for it, so let's go // try to fetch the state. var documentState = _solution.State.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (documentState == null) { return null; } return ImmutableHashMapExtensions.GetOrAdd(ref _idToSourceGeneratedDocumentMap, documentId, s_createSourceGeneratedDocumentFunction, (documentState, this)); } internal async Task<bool> ContainsSymbolsWithNameAsync(string name, SymbolFilter filter, CancellationToken cancellationToken) { return this.SupportsCompilation && await _solution.State.ContainsSymbolsWithNameAsync(Id, name, filter, cancellationToken).ConfigureAwait(false); } internal async Task<bool> ContainsSymbolsWithNameAsync(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { return this.SupportsCompilation && await _solution.State.ContainsSymbolsWithNameAsync(Id, predicate, filter, cancellationToken).ConfigureAwait(false); } private static readonly Func<DocumentId, Project, Document?> s_tryCreateDocumentFunction = (documentId, project) => project._projectState.DocumentStates.TryGetState(documentId, out var state) ? new Document(project, state) : null; private static readonly Func<DocumentId, Project, AdditionalDocument?> s_tryCreateAdditionalDocumentFunction = (documentId, project) => project._projectState.AdditionalDocumentStates.TryGetState(documentId, out var state) ? new AdditionalDocument(project, state) : null; private static readonly Func<DocumentId, Project, AnalyzerConfigDocument?> s_tryCreateAnalyzerConfigDocumentFunction = (documentId, project) => project._projectState.AnalyzerConfigDocumentStates.TryGetState(documentId, out var state) ? new AnalyzerConfigDocument(project, state) : null; private static readonly Func<DocumentId, (SourceGeneratedDocumentState state, Project project), SourceGeneratedDocument> s_createSourceGeneratedDocumentFunction = (documentId, stateAndProject) => new SourceGeneratedDocument(stateAndProject.project, stateAndProject.state); /// <summary> /// Tries to get the cached <see cref="Compilation"/> for this project if it has already been created and is still cached. In almost all /// cases you should call <see cref="GetCompilationAsync"/> which will either return the cached <see cref="Compilation"/> /// or create a new one otherwise. /// </summary> public bool TryGetCompilation([NotNullWhen(returnValue: true)] out Compilation? compilation) => _solution.State.TryGetCompilation(this.Id, out compilation); /// <summary> /// Get the <see cref="Compilation"/> for this project asynchronously. /// </summary> /// <returns> /// Returns the produced <see cref="Compilation"/>, or <see langword="null"/> if <see /// cref="SupportsCompilation"/> returns <see langword="false"/>. This function will /// return the same value if called multiple times. /// </returns> public Task<Compilation?> GetCompilationAsync(CancellationToken cancellationToken = default) => _solution.State.GetCompilationAsync(_projectState, cancellationToken); /// <summary> /// Determines if the compilation returned by <see cref="GetCompilationAsync"/> and all its referenced compilation are from fully loaded projects. /// </summary> // TODO: make this public internal Task<bool> HasSuccessfullyLoadedAsync(CancellationToken cancellationToken = default) => _solution.State.HasSuccessfullyLoadedAsync(_projectState, cancellationToken); /// <summary> /// Gets an object that lists the added, changed and removed documents between this project and the specified project. /// </summary> public ProjectChanges GetChanges(Project oldProject) { if (oldProject == null) { throw new ArgumentNullException(nameof(oldProject)); } return new ProjectChanges(this, oldProject); } /// <summary> /// The project version. This equates to the version of the project file. /// </summary> public VersionStamp Version => _projectState.Version; /// <summary> /// The version of the most recently modified document. /// </summary> public Task<VersionStamp> GetLatestDocumentVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetLatestDocumentVersionAsync(cancellationToken); /// <summary> /// The most recent version of the project, its documents and all dependent projects and documents. /// </summary> public Task<VersionStamp> GetDependentVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project including the semantics of referenced projects. /// This version changes whenever the consumable declarations of this project and/or projects it depends on change. /// </summary> public Task<VersionStamp> GetDependentSemanticVersionAsync(CancellationToken cancellationToken = default) => _solution.State.GetDependentSemanticVersionAsync(this.Id, cancellationToken); /// <summary> /// The semantic version of this project not including the semantics of referenced projects. /// This version changes only when the consumable declarations of this project change. /// </summary> public Task<VersionStamp> GetSemanticVersionAsync(CancellationToken cancellationToken = default) => _projectState.GetSemanticVersionAsync(cancellationToken); /// <summary> /// Creates a new instance of this project updated to have the new assembly name. /// </summary> public Project WithAssemblyName(string assemblyName) => this.Solution.WithProjectAssemblyName(this.Id, assemblyName).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the new default namespace. /// </summary> public Project WithDefaultNamespace(string defaultNamespace) => this.Solution.WithProjectDefaultNamespace(this.Id, defaultNamespace).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified compilation options. /// </summary> public Project WithCompilationOptions(CompilationOptions options) => this.Solution.WithProjectCompilationOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to have the specified parse options. /// </summary> public Project WithParseOptions(ParseOptions options) => this.Solution.WithProjectParseOptions(this.Id, options).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project reference /// in addition to already existing ones. /// </summary> public Project AddProjectReference(ProjectReference projectReference) => this.Solution.AddProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified project references /// in addition to already existing ones. /// </summary> public Project AddProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.AddProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified project reference. /// </summary> public Project RemoveProjectReference(ProjectReference projectReference) => this.Solution.RemoveProjectReference(this.Id, projectReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing project references /// with the specified ones. /// </summary> public Project WithProjectReferences(IEnumerable<ProjectReference> projectReferences) => this.Solution.WithProjectReferences(this.Id, projectReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata reference /// in addition to already existing ones. /// </summary> public Project AddMetadataReference(MetadataReference metadataReference) => this.Solution.AddMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified metadata references /// in addition to already existing ones. /// </summary> public Project AddMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.AddMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified metadata reference. /// </summary> public Project RemoveMetadataReference(MetadataReference metadataReference) => this.Solution.RemoveMetadataReference(this.Id, metadataReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing metadata reference /// with the specified ones. /// </summary> public Project WithMetadataReferences(IEnumerable<MetadataReference> metadataReferences) => this.Solution.WithProjectMetadataReferences(this.Id, metadataReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer reference /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.AddAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to include the specified analyzer references /// in addition to already existing ones. /// </summary> public Project AddAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferences) => this.Solution.AddAnalyzerReferences(this.Id, analyzerReferences).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer reference. /// </summary> public Project RemoveAnalyzerReference(AnalyzerReference analyzerReference) => this.Solution.RemoveAnalyzerReference(this.Id, analyzerReference).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to replace existing analyzer references /// with the specified ones. /// </summary> public Project WithAnalyzerReferences(IEnumerable<AnalyzerReference> analyzerReferencs) => this.Solution.WithProjectAnalyzerReferences(this.Id, analyzerReferencs).GetProject(this.Id)!; /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SyntaxNode syntaxRoot, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); // use preserve identity for forked solution directly from syntax node. // this lets us not serialize temporary tree unnecessarily return this.Solution.AddDocument(id, name, syntaxRoot, folders, filePath, preservationMode: PreservationMode.PreserveIdentity).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new document in a new instance of this project. /// </summary> public Document AddDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id, debugName: name); return this.Solution.AddDocument(id, name, text, folders, filePath).GetDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new additional document in a new instance of this project. /// </summary> public TextDocument AddAdditionalDocument(string name, string text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAdditionalDocument(id, name, text, folders, filePath).GetAdditionalDocument(id)!; } /// <summary> /// Creates a new analyzer config document in a new instance of this project. /// </summary> public TextDocument AddAnalyzerConfigDocument(string name, SourceText text, IEnumerable<string>? folders = null, string? filePath = null) { var id = DocumentId.CreateNewId(this.Id); return this.Solution.AddAnalyzerConfigDocument(id, name, text, folders, filePath).GetAnalyzerConfigDocument(id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified document. /// </summary> public Project RemoveDocument(DocumentId documentId) { // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. return this.Solution.RemoveDocument(documentId).GetProject(this.Id)!; } /// <summary> /// Creates a new instance of this project updated to no longer include the specified documents. /// </summary> public Project RemoveDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional document. /// </summary> public Project RemoveAdditionalDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAdditionalDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new instance of this project updated to no longer include the specified additional documents. /// </summary> public Project RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAdditionalDocuments(documentIds).GetRequiredProject(this.Id); } /// <summary> /// Creates a new instance of this project updated to no longer include the specified analyzer config document. /// </summary> public Project RemoveAnalyzerConfigDocument(DocumentId documentId) // NOTE: the method isn't checking if documentId belongs to the project. This probably should be done, but may be a compat change. // https://github.com/dotnet/roslyn/issues/41211 tracks this investigation. => this.Solution.RemoveAnalyzerConfigDocument(documentId).GetProject(this.Id)!; /// <summary> /// Creates a new solution instance that no longer includes the specified <see cref="AnalyzerConfigDocument"/>s. /// </summary> public Project RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { CheckIdsContainedInProject(documentIds); return this.Solution.RemoveAnalyzerConfigDocuments(documentIds).GetRequiredProject(this.Id); } private void CheckIdsContainedInProject(ImmutableArray<DocumentId> documentIds) { foreach (var documentId in documentIds) { // Dealing with nulls is handled by the caller of this if (documentId?.ProjectId != this.Id) { throw new ArgumentException(string.Format(WorkspacesResources._0_is_in_a_different_project, documentId)); } } } internal AnalyzerConfigOptionsResult? GetAnalyzerConfigOptions() => _projectState.GetAnalyzerConfigOptions(); private string GetDebuggerDisplay() => this.Name; internal SkippedHostAnalyzersInfo GetSkippedAnalyzersInfo(DiagnosticAnalyzerInfoCache infoCache) => Solution.State.Analyzers.GetSkippedAnalyzersInfo(this, infoCache); } }
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.CompilationTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool HasCompilation { get { var state = this.ReadState(); return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// get all syntax trees that contain declaration node with the given name /// </summary> public IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.DeclarationOnlyCompilation == null) { return null; } // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. // use cloned compilation since this will cause symbols to be created. var clone = state.DeclarationOnlyCompilation.Clone(); return clone.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree)); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// Tracks the changes made to a project and provides the facility to get a lazily built /// compilation for that project. As the compilation is being built, the partial results are /// stored as well so that they can be used in the 'in progress' workspace snapshot. /// </summary> private partial class CompilationTracker : ICompilationTracker { private static readonly Func<ProjectState, string> s_logBuildCompilationAsync = state => string.Join(",", state.AssemblyName, state.DocumentStates.Count); public ProjectState ProjectState { get; } /// <summary> /// Access via the <see cref="ReadState"/> and <see cref="WriteState"/> methods. /// </summary> private State _stateDoNotAccessDirectly; // guarantees only one thread is building at a time private readonly SemaphoreSlim _buildLock = new(initialCount: 1); private CompilationTracker( ProjectState project, State state) { Contract.ThrowIfNull(project); this.ProjectState = project; _stateDoNotAccessDirectly = state; } /// <summary> /// Creates a tracker for the provided project. The tracker will be in the 'empty' state /// and will have no extra information beyond the project itself. /// </summary> public CompilationTracker(ProjectState project) : this(project, State.Empty) { } private State ReadState() => Volatile.Read(ref _stateDoNotAccessDirectly); private void WriteState(State state, SolutionServices solutionServices) { if (solutionServices.SupportsCachingRecoverableObjects) { // Allow the cache service to create a strong reference to the compilation. We'll get the "furthest along" compilation we have // and hold onto that. var compilationToCache = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull() ?? state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(); solutionServices.CacheService.CacheObjectIfCachingEnabledForKey(ProjectState.Id, state, compilationToCache); } Volatile.Write(ref _stateDoNotAccessDirectly, state); } public bool HasCompilation { get { var state = this.ReadState(); return state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out _) || state.DeclarationOnlyCompilation != null; } } public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { Debug.Assert(symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.NetModule || symbol.Kind == SymbolKind.DynamicType); var state = this.ReadState(); var unrootedSymbolSet = (state as FinalState)?.UnrootedSymbolSet; if (unrootedSymbolSet == null) { // this was not a tracker that has handed out a compilation (all compilations handed out must be // owned by a 'FinalState'). So this symbol could not be from us. return false; } return unrootedSymbolSet.Value.ContainsAssemblyOrModuleOrDynamic(symbol, primary); } /// <summary> /// Creates a new instance of the compilation info, retaining any already built /// compilation state as the now 'old' state /// </summary> public ICompilationTracker Fork( ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { var state = ReadState(); var baseCompilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (baseCompilation != null) { var intermediateProjects = state is InProgressState inProgressState ? inProgressState.IntermediateProjects : ImmutableArray.Create<(ProjectState oldState, CompilationAndGeneratorDriverTranslationAction action)>(); if (translate is not null) { // We have a translation action; are we able to merge it with the prior one? var merged = false; if (intermediateProjects.Any()) { var (priorState, priorAction) = intermediateProjects.Last(); var mergedTranslation = translate.TryMergeWithPrior(priorAction); if (mergedTranslation != null) { // We can replace the prior action with this new one intermediateProjects = intermediateProjects.SetItem(intermediateProjects.Length - 1, (oldState: priorState, mergedTranslation)); merged = true; } } if (!merged) { // Just add it to the end intermediateProjects = intermediateProjects.Add((oldState: this.ProjectState, translate)); } } var newState = State.Create(baseCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects); return new CompilationTracker(newProject, newState); } var declarationOnlyCompilation = state.DeclarationOnlyCompilation; if (declarationOnlyCompilation != null) { if (translate != null) { var intermediateProjects = ImmutableArray.Create((this.ProjectState, translate)); return new CompilationTracker(newProject, new InProgressState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, compilationWithGeneratedDocuments: state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken), intermediateProjects)); } return new CompilationTracker(newProject, new LightDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, generatedDocumentsAreFinal: false)); } // We have nothing. Just make a tracker that only points to the new project. We'll have // to rebuild its compilation from scratch if anyone asks for it. return new CompilationTracker(newProject); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { GetPartialCompilationState( solution, docState.Id, out var inProgressProject, out var inProgressCompilation, out var sourceGeneratedDocuments, out var generatorDriver, out var metadataReferenceToProjectId, cancellationToken); if (!inProgressCompilation.SyntaxTrees.Contains(tree)) { var existingTree = inProgressCompilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == tree.FilePath); if (existingTree != null) { inProgressCompilation = inProgressCompilation.ReplaceSyntaxTree(existingTree, tree); inProgressProject = inProgressProject.UpdateDocument(docState, textChanged: false, recalculateDependentVersions: false); } else { inProgressCompilation = inProgressCompilation.AddSyntaxTrees(tree); Debug.Assert(!inProgressProject.DocumentStates.Contains(docState.Id)); inProgressProject = inProgressProject.AddDocuments(ImmutableArray.Create(docState)); } } // The user is asking for an in progress snap. We don't want to create it and then // have the compilation immediately disappear. So we force it to stay around with a ConstantValueSource. // As a policy, all partial-state projects are said to have incomplete references, since the state has no guarantees. var finalState = FinalState.Create( new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), new ConstantValueSource<Optional<Compilation>>(inProgressCompilation), inProgressCompilation, hasSuccessfullyLoaded: false, sourceGeneratedDocuments, generatorDriver, inProgressCompilation, this.ProjectState.Id, metadataReferenceToProjectId); return new CompilationTracker(inProgressProject, finalState); } /// <summary> /// Tries to get the latest snapshot of the compilation without waiting for it to be /// fully built. This method takes advantage of the progress side-effect produced during /// <see cref="BuildCompilationInfoAsync(SolutionState, CancellationToken)"/>. /// It will either return the already built compilation, any /// in-progress compilation or any known old compilation in that order of preference. /// The compilation state that is returned will have a compilation that is retained so /// that it cannot disappear. /// </summary> /// <param name="inProgressCompilation">The compilation to return. Contains any source generated documents that were available already added.</param> private void GetPartialCompilationState( SolutionState solution, DocumentId id, out ProjectState inProgressProject, out Compilation inProgressCompilation, out TextDocumentStates<SourceGeneratedDocumentState> sourceGeneratedDocuments, out GeneratorDriver? generatorDriver, out Dictionary<MetadataReference, ProjectId>? metadataReferenceToProjectId, CancellationToken cancellationToken) { var state = ReadState(); var compilationWithoutGeneratedDocuments = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // check whether we can bail out quickly for typing case var inProgressState = state as InProgressState; sourceGeneratedDocuments = state.GeneratedDocuments; generatorDriver = state.GeneratorDriver; // all changes left for this document is modifying the given document. // we can use current state as it is since we will replace the document with latest document anyway. if (inProgressState != null && compilationWithoutGeneratedDocuments != null && inProgressState.IntermediateProjects.All(t => IsTouchDocumentActionForDocument(t.action, id))) { inProgressProject = ProjectState; // We'll add in whatever generated documents we do have; these may be from a prior run prior to some changes // being made to the project, but it's the best we have so we'll use it. inProgressCompilation = compilationWithoutGeneratedDocuments.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // This is likely a bug. It seems possible to pass out a partial compilation state that we don't // properly record assembly symbols for. metadataReferenceToProjectId = null; SolutionLogger.UseExistingPartialProjectState(); return; } inProgressProject = inProgressState != null ? inProgressState.IntermediateProjects.First().oldState : this.ProjectState; // if we already have a final compilation we are done. if (compilationWithoutGeneratedDocuments != null && state is FinalState finalState) { var finalCompilation = finalState.FinalCompilationWithGeneratedDocuments.GetValueOrNull(cancellationToken); if (finalCompilation != null) { inProgressCompilation = finalCompilation; // This should hopefully be safe to return as null. Because we already reached the 'FinalState' // before, we should have already recorded the assembly symbols for it. So not recording them // again is likely ok (as long as compilations continue to return the same IAssemblySymbols for // the same references across source edits). metadataReferenceToProjectId = null; SolutionLogger.UseExistingFullProjectState(); return; } } // 1) if we have an in-progress compilation use it. // 2) If we don't, then create a simple empty compilation/project. // 3) then, make sure that all it's p2p refs and whatnot are correct. if (compilationWithoutGeneratedDocuments == null) { inProgressProject = inProgressProject.RemoveAllDocuments(); inProgressCompilation = CreateEmptyCompilation(); } else { inProgressCompilation = compilationWithoutGeneratedDocuments; } inProgressCompilation = inProgressCompilation.AddSyntaxTrees(sourceGeneratedDocuments.States.Values.Select(state => state.GetSyntaxTree(cancellationToken))); // Now add in back a consistent set of project references. For project references // try to get either a CompilationReference or a SkeletonReference. This ensures // that the in-progress project only reports a reference to another project if it // could actually get a reference to that project's metadata. var metadataReferences = new List<MetadataReference>(); var newProjectReferences = new List<ProjectReference>(); metadataReferences.AddRange(this.ProjectState.MetadataReferences); metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); if (referencedProject != null) { if (referencedProject.IsSubmission) { var previousScriptCompilation = solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).WaitAndGetResult(cancellationToken); // previous submission project must support compilation: RoslynDebug.Assert(previousScriptCompilation != null); inProgressCompilation = inProgressCompilation.WithScriptCompilationInfo(inProgressCompilation.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousScriptCompilation)); } else { // get the latest metadata for the partial compilation of the referenced project. var metadata = solution.GetPartialMetadataReference(projectReference, this.ProjectState); if (metadata == null) { // if we failed to get the metadata, check to see if we previously had existing metadata and reuse it instead. var inProgressCompilationNotRef = inProgressCompilation; metadata = inProgressCompilationNotRef.ExternalReferences.FirstOrDefault( r => solution.GetProjectState(inProgressCompilationNotRef.GetAssemblyOrModuleSymbol(r) as IAssemblySymbol)?.Id == projectReference.ProjectId); } if (metadata != null) { newProjectReferences.Add(projectReference); metadataReferences.Add(metadata); metadataReferenceToProjectId.Add(metadata, projectReference.ProjectId); } } } } inProgressProject = inProgressProject.WithProjectReferences(newProjectReferences); if (!Enumerable.SequenceEqual(inProgressCompilation.ExternalReferences, metadataReferences)) { inProgressCompilation = inProgressCompilation.WithReferences(metadataReferences); } SolutionLogger.CreatePartialProjectState(); } private static bool IsTouchDocumentActionForDocument(CompilationAndGeneratorDriverTranslationAction action, DocumentId id) => action is CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction touchDocumentAction && touchDocumentAction.DocumentId == id; /// <summary> /// Gets the final compilation if it is available. /// </summary> public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { var state = ReadState(); if (state.FinalCompilationWithGeneratedDocuments != null && state.FinalCompilationWithGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue) { compilation = compilationOpt.Value; return true; } compilation = null; return false; } public Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { if (this.TryGetCompilation(out var compilation)) { // PERF: This is a hot code path and Task<TResult> isn't cheap, // so cache the completed tasks to reduce allocations. We also // need to avoid keeping a strong reference to the Compilation, // so use a ConditionalWeakTable. return SpecializedTasks.FromResult(compilation); } else { return GetCompilationSlowAsync(solution, cancellationToken); } } private async Task<Compilation> GetCompilationSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.Compilation; } private async Task<Compilation> GetOrBuildDeclarationCompilationAsync(SolutionServices solutionServices, CancellationToken cancellationToken) { try { cancellationToken.ThrowIfCancellationRequested(); using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { var state = ReadState(); // we are already in the final stage. just return it. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { return compilation; } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation == null) { // let's see whether we have declaration only compilation if (state.DeclarationOnlyCompilation != null) { // okay, move to full declaration state. do this so that declaration only compilation never // realize symbols. var declarationOnlyCompilation = state.DeclarationOnlyCompilation.Clone(); WriteState(new FullDeclarationState(declarationOnlyCompilation, state.GeneratedDocuments, state.GeneratorDriver, state.GeneratedDocumentsAreFinal), solutionServices); return declarationOnlyCompilation; } // We've got nothing. Build it from scratch :( return await BuildDeclarationCompilationFromScratchAsync(solutionServices, cancellationToken).ConfigureAwait(false); } if (state is FullDeclarationState or FinalState) { // we have full declaration, just use it. return compilation; } (compilation, _, _) = await BuildDeclarationCompilationFromInProgressAsync(solutionServices, (InProgressState)state, compilation, cancellationToken).ConfigureAwait(false); // We must have an in progress compilation. Build off of that. return compilation; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<CompilationInfo> GetOrBuildCompilationInfoAsync( SolutionState solution, bool lockGate, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_Project_CompilationTracker_BuildCompilationAsync, s_logBuildCompilationAsync, ProjectState, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // Try to get the built compilation. If it exists, then we can just return that. var finalCompilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (finalCompilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return new CompilationInfo(finalCompilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments); } // Otherwise, we actually have to build it. Ensure that only one thread is trying to // build this compilation at a time. if (lockGate) { using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } else { return await BuildCompilationInfoAsync(solution, cancellationToken).ConfigureAwait(false); } } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Builds the compilation matching the project state. In the process of building, also /// produce in progress snapshots that can be accessed from other threads. /// </summary> private Task<CompilationInfo> BuildCompilationInfoAsync( SolutionState solution, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var state = ReadState(); // if we already have a compilation, we must be already done! This can happen if two // threads were waiting to build, and we came in after the other succeeded. var compilation = state.FinalCompilationWithGeneratedDocuments?.GetValueOrNull(cancellationToken); if (compilation != null) { RoslynDebug.Assert(state.HasSuccessfullyLoaded.HasValue); return Task.FromResult(new CompilationInfo(compilation, state.HasSuccessfullyLoaded.Value, state.GeneratedDocuments)); } compilation = state.CompilationWithoutGeneratedDocuments?.GetValueOrNull(cancellationToken); // If we have already reached FinalState in the past but the compilation was garbage collected, we still have the generated documents // so we can pass those to FinalizeCompilationAsync to avoid the recomputation. This is necessary for correctness as otherwise // we'd be reparsing trees which could result in generated documents changing identity. var authoritativeGeneratedDocuments = state.GeneratedDocumentsAreFinal ? state.GeneratedDocuments : (TextDocumentStates<SourceGeneratedDocumentState>?)null; var nonAuthoritativeGeneratedDocuments = state.GeneratedDocuments; var generatorDriver = state.GeneratorDriver; if (compilation == null) { // this can happen if compilation is already kicked out from the cache. // check whether the state we have support declaration only compilation if (state.DeclarationOnlyCompilation != null) { // we have declaration only compilation. build final one from it. return FinalizeCompilationAsync(solution, state.DeclarationOnlyCompilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } // We've got nothing. Build it from scratch :( return BuildCompilationInfoFromScratchAsync(solution, cancellationToken); } if (state is FullDeclarationState or FinalState) { // We have a declaration compilation, use it to reconstruct the final compilation return FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments, nonAuthoritativeGeneratedDocuments, compilationWithStaleGeneratedTrees: null, generatorDriver, cancellationToken); } else { // We must have an in progress compilation. Build off of that. return BuildFinalStateFromInProgressStateAsync(solution, (InProgressState)state, compilation, cancellationToken); } } private async Task<CompilationInfo> BuildCompilationInfoFromScratchAsync( SolutionState solution, CancellationToken cancellationToken) { try { var compilation = await BuildDeclarationCompilationFromScratchAsync(solution.Services, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilation, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: TextDocumentStates<SourceGeneratedDocumentState>.Empty, compilationWithStaleGeneratedTrees: null, generatorDriver: null, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid calling " + nameof(Compilation.AddSyntaxTrees) + " in a loop due to allocation overhead.")] private async Task<Compilation> BuildDeclarationCompilationFromScratchAsync( SolutionServices solutionServices, CancellationToken cancellationToken) { try { var compilation = CreateEmptyCompilation(); var trees = ArrayBuilder<SyntaxTree>.GetInstance(ProjectState.DocumentStates.Count); foreach (var documentState in ProjectState.DocumentStates.GetStatesInCompilationOrder()) { cancellationToken.ThrowIfCancellationRequested(); // Include the tree even if the content of the document failed to load. trees.Add(await documentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } compilation = compilation.AddSyntaxTrees(trees); trees.Free(); WriteState(new FullDeclarationState(compilation, TextDocumentStates<SourceGeneratedDocumentState>.Empty, generatorDriver: null, generatedDocumentsAreFinal: false), solutionServices); return compilation; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private Compilation CreateEmptyCompilation() { var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); if (this.ProjectState.IsSubmission) { return compilationFactory.CreateSubmissionCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!, this.ProjectState.HostObjectType); } else { return compilationFactory.CreateCompilation( this.ProjectState.AssemblyName, this.ProjectState.CompilationOptions!); } } private async Task<CompilationInfo> BuildFinalStateFromInProgressStateAsync( SolutionState solution, InProgressState state, Compilation inProgressCompilation, CancellationToken cancellationToken) { try { var (compilationWithoutGenerators, compilationWithGenerators, generatorDriver) = await BuildDeclarationCompilationFromInProgressAsync(solution.Services, state, inProgressCompilation, cancellationToken).ConfigureAwait(false); return await FinalizeCompilationAsync( solution, compilationWithoutGenerators, authoritativeGeneratedDocuments: null, nonAuthoritativeGeneratedDocuments: state.GeneratedDocuments, compilationWithGenerators, generatorDriver, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private async Task<(Compilation compilationWithoutGenerators, Compilation? compilationWithGenerators, GeneratorDriver? generatorDriver)> BuildDeclarationCompilationFromInProgressAsync( SolutionServices solutionServices, InProgressState state, Compilation compilationWithoutGenerators, CancellationToken cancellationToken) { try { var compilationWithGenerators = state.CompilationWithGeneratedDocuments; var generatorDriver = state.GeneratorDriver; // If compilationWithGenerators is the same as compilationWithoutGenerators, then it means a prior run of generators // didn't produce any files. In that case, we'll just make compilationWithGenerators null so we avoid doing any // transformations of it multiple times. Otherwise the transformations below and in FinalizeCompilationAsync will try // to update both at once, which is functionally fine but just unnecessary work. This function is always allowed to return // null for compilationWithGenerators in the end, so there's no harm there. if (compilationWithGenerators == compilationWithoutGenerators) { compilationWithGenerators = null; } var intermediateProjects = state.IntermediateProjects; while (intermediateProjects.Length > 0) { cancellationToken.ThrowIfCancellationRequested(); // We have a list of transformations to get to our final compilation; take the first transformation and apply it. var intermediateProject = intermediateProjects[0]; compilationWithoutGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithoutGenerators, cancellationToken).ConfigureAwait(false); if (compilationWithGenerators != null) { // Also transform the compilation that has generated files; we won't do that though if the transformation either would cause problems with // the generated documents, or if don't have any source generators in the first place. if (intermediateProject.action.CanUpdateCompilationWithStaleGeneratedTreesIfGeneratorsGiveSameOutput && intermediateProject.oldState.SourceGenerators.Any()) { compilationWithGenerators = await intermediateProject.action.TransformCompilationAsync(compilationWithGenerators, cancellationToken).ConfigureAwait(false); } else { compilationWithGenerators = null; } } if (generatorDriver != null) { generatorDriver = intermediateProject.action.TransformGeneratorDriver(generatorDriver); } // We have updated state, so store this new result; this allows us to drop the intermediate state we already processed // even if we were to get cancelled at a later point. intermediateProjects = intermediateProjects.RemoveAt(0); this.WriteState(State.Create(compilationWithoutGenerators, state.GeneratedDocuments, generatorDriver, compilationWithGenerators, intermediateProjects), solutionServices); } return (compilationWithoutGenerators, compilationWithGenerators, generatorDriver); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private readonly struct CompilationInfo { public Compilation Compilation { get; } public bool HasSuccessfullyLoaded { get; } public TextDocumentStates<SourceGeneratedDocumentState> GeneratedDocuments { get; } public CompilationInfo(Compilation compilation, bool hasSuccessfullyLoaded, TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments) { Compilation = compilation; HasSuccessfullyLoaded = hasSuccessfullyLoaded; GeneratedDocuments = generatedDocuments; } } /// <summary> /// Add all appropriate references to the compilation and set it as our final compilation /// state. /// </summary> /// <param name="authoritativeGeneratedDocuments">The generated documents that can be used since they are already /// known to be correct for the given state. This would be non-null in cases where we had computed everything and /// ran generators, but then the compilation was garbage collected and are re-creating a compilation but we /// still had the prior generated result available.</param> /// <param name="nonAuthoritativeGeneratedDocuments">The generated documents from a previous pass which may /// or may not be correct for the current compilation. These states may be used to access cached results, if /// and when applicable for the current compilation.</param> /// <param name="compilationWithStaleGeneratedTrees">The compilation from a prior run that contains generated trees, which /// match the states included in <paramref name="nonAuthoritativeGeneratedDocuments"/>. If a generator run here produces /// the same set of generated documents as are in <paramref name="nonAuthoritativeGeneratedDocuments"/>, and we don't need to make any other /// changes to references, we can then use this compilation instead of re-adding source generated files again to the /// <paramref name="compilationWithoutGenerators"/>.</param> /// <param name="generatorDriver">The generator driver that can be reused for this finalization.</param> private async Task<CompilationInfo> FinalizeCompilationAsync( SolutionState solution, Compilation compilationWithoutGenerators, TextDocumentStates<SourceGeneratedDocumentState>? authoritativeGeneratedDocuments, TextDocumentStates<SourceGeneratedDocumentState> nonAuthoritativeGeneratedDocuments, Compilation? compilationWithStaleGeneratedTrees, GeneratorDriver? generatorDriver, CancellationToken cancellationToken) { try { // if HasAllInformation is false, then this project is always not completed. var hasSuccessfullyLoaded = this.ProjectState.HasAllInformation; var newReferences = new List<MetadataReference>(); var metadataReferenceToProjectId = new Dictionary<MetadataReference, ProjectId>(); newReferences.AddRange(this.ProjectState.MetadataReferences); foreach (var projectReference in this.ProjectState.ProjectReferences) { var referencedProject = solution.GetProjectState(projectReference.ProjectId); // Even though we're creating a final compilation (vs. an in progress compilation), // it's possible that the target project has been removed. if (referencedProject != null) { // If both projects are submissions, we'll count this as a previous submission link // instead of a regular metadata reference if (referencedProject.IsSubmission) { // if the referenced project is a submission project must be a submission as well: Debug.Assert(this.ProjectState.IsSubmission); // We now need to (potentially) update the prior submission compilation. That Compilation is held in the // ScriptCompilationInfo that we need to replace as a unit. var previousSubmissionCompilation = await solution.GetCompilationAsync(projectReference.ProjectId, cancellationToken).ConfigureAwait(false); if (compilationWithoutGenerators.ScriptCompilationInfo!.PreviousScriptCompilation != previousSubmissionCompilation) { compilationWithoutGenerators = compilationWithoutGenerators.WithScriptCompilationInfo( compilationWithoutGenerators.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithScriptCompilationInfo( compilationWithStaleGeneratedTrees.ScriptCompilationInfo!.WithPreviousScriptCompilation(previousSubmissionCompilation!)); } } else { var metadataReference = await solution.GetMetadataReferenceAsync( projectReference, this.ProjectState, cancellationToken).ConfigureAwait(false); // A reference can fail to be created if a skeleton assembly could not be constructed. if (metadataReference != null) { newReferences.Add(metadataReference); metadataReferenceToProjectId.Add(metadataReference, projectReference.ProjectId); } else { hasSuccessfullyLoaded = false; } } } } // Now that we know the set of references this compilation should have, update them if they're not already. // Generators cannot add references, so we can use the same set of references both for the compilation // that doesn't have generated files, and the one we're trying to reuse that has generated files. // Since we updated both of these compilations together in response to edits, we only have to check one // for a potential mismatch. if (!Enumerable.SequenceEqual(compilationWithoutGenerators.ExternalReferences, newReferences)) { compilationWithoutGenerators = compilationWithoutGenerators.WithReferences(newReferences); compilationWithStaleGeneratedTrees = compilationWithStaleGeneratedTrees?.WithReferences(newReferences); } // We will finalize the compilation by adding full contents here. // TODO: allow finalize compilation to incrementally update a prior version // https://github.com/dotnet/roslyn/issues/46418 Compilation compilationWithGenerators; TextDocumentStates<SourceGeneratedDocumentState> generatedDocuments; if (authoritativeGeneratedDocuments.HasValue) { generatedDocuments = authoritativeGeneratedDocuments.Value; compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } else { using var generatedDocumentsBuilder = new TemporaryArray<SourceGeneratedDocumentState>(); if (ProjectState.SourceGenerators.Any()) { // If we don't already have a generator driver, we'll have to create one from scratch if (generatorDriver == null) { var additionalTexts = this.ProjectState.AdditionalDocumentStates.SelectAsArray(static documentState => documentState.AdditionalText); var compilationFactory = this.ProjectState.LanguageServices.GetRequiredService<ICompilationFactoryService>(); generatorDriver = compilationFactory.CreateGeneratorDriver( this.ProjectState.ParseOptions!, ProjectState.SourceGenerators, this.ProjectState.AnalyzerOptions.AnalyzerConfigOptionsProvider, additionalTexts); } generatorDriver = generatorDriver.RunGenerators(compilationWithoutGenerators, cancellationToken); var runResult = generatorDriver.GetRunResult(); // We may be able to reuse compilationWithStaleGeneratedTrees if the generated trees are identical. We will assign null // to compilationWithStaleGeneratedTrees if we at any point realize it can't be used. We'll first check the count of trees // if that changed then we absolutely can't reuse it. But if the counts match, we'll then see if each generated tree // content is identical to the prior generation run; if we find a match each time, then the set of the generated trees // and the prior generated trees are identical. if (compilationWithStaleGeneratedTrees != null) { if (nonAuthoritativeGeneratedDocuments.Count != runResult.Results.Sum(r => r.GeneratedSources.Length)) { compilationWithStaleGeneratedTrees = null; } } foreach (var generatorResult in runResult.Results) { foreach (var generatedSource in generatorResult.GeneratedSources) { var existing = FindExistingGeneratedDocumentState( nonAuthoritativeGeneratedDocuments, generatorResult.Generator, generatedSource.HintName); if (existing != null) { var newDocument = existing.WithUpdatedGeneratedContent( generatedSource.SourceText, this.ProjectState.ParseOptions!); generatedDocumentsBuilder.Add(newDocument); if (newDocument != existing) compilationWithStaleGeneratedTrees = null; } else { // NOTE: the use of generatedSource.SyntaxTree to fetch the path and options is OK, // since the tree is a lazy tree and that won't trigger the parse. var identity = SourceGeneratedDocumentIdentity.Generate( ProjectState.Id, generatedSource.HintName, generatorResult.Generator, generatedSource.SyntaxTree.FilePath); generatedDocumentsBuilder.Add( SourceGeneratedDocumentState.Create( identity, generatedSource.SourceText, generatedSource.SyntaxTree.Options, this.ProjectState.LanguageServices, solution.Services)); // The count of trees was the same, but something didn't match up. Since we're here, at least one tree // was added, and an equal number must have been removed. Rather than trying to incrementally update // this compilation, we'll just toss this and re-add all the trees. compilationWithStaleGeneratedTrees = null; } } } } // If we didn't null out this compilation, it means we can actually use it if (compilationWithStaleGeneratedTrees != null) { generatedDocuments = nonAuthoritativeGeneratedDocuments; compilationWithGenerators = compilationWithStaleGeneratedTrees; } else { generatedDocuments = new TextDocumentStates<SourceGeneratedDocumentState>(generatedDocumentsBuilder.ToImmutableAndClear()); compilationWithGenerators = compilationWithoutGenerators.AddSyntaxTrees( await generatedDocuments.States.Values.SelectAsArrayAsync(state => state.GetSyntaxTreeAsync(cancellationToken)).ConfigureAwait(false)); } } var finalState = FinalState.Create( State.CreateValueSource(compilationWithGenerators, solution.Services), State.CreateValueSource(compilationWithoutGenerators, solution.Services), compilationWithoutGenerators, hasSuccessfullyLoaded, generatedDocuments, generatorDriver, compilationWithGenerators, this.ProjectState.Id, metadataReferenceToProjectId); this.WriteState(finalState, solution.Services); return new CompilationInfo(compilationWithGenerators, hasSuccessfullyLoaded, generatedDocuments); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } // Local functions static SourceGeneratedDocumentState? FindExistingGeneratedDocumentState( TextDocumentStates<SourceGeneratedDocumentState> states, ISourceGenerator generator, string hintName) { var generatorAssemblyName = SourceGeneratedDocumentIdentity.GetGeneratorAssemblyName(generator); var generatorTypeName = SourceGeneratedDocumentIdentity.GetGeneratorTypeName(generator); foreach (var (_, state) in states.States) { if (state.SourceGeneratorAssemblyName != generatorAssemblyName) continue; if (state.SourceGeneratorTypeName != generatorTypeName) continue; if (state.HintName != hintName) continue; return state; } return null; } } public async Task<MetadataReference> GetMetadataReferenceAsync( SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out var compilation)) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempts to get (without waiting) a metadata reference to a possibly in progress /// compilation. Only actual compilation references are returned. Could potentially /// return null if nothing can be provided. /// </summary> public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { var state = ReadState(); // get compilation in any state it happens to be in right now. if (state.CompilationWithoutGeneratedDocuments != null && state.CompilationWithoutGeneratedDocuments.TryGetValue(out var compilationOpt) && compilationOpt.HasValue && ProjectState.LanguageServices == fromProject.LanguageServices) { // if we have a compilation and its the correct language, use a simple compilation reference return compilationOpt.Value.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } return null; } /// <summary> /// Gets a metadata reference to the metadata-only-image corresponding to the compilation. /// </summary> private async Task<MetadataReference> GetMetadataOnlyImageReferenceAsync( SolutionState solution, ProjectReference projectReference, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.Workspace_SkeletonAssembly_GetMetadataOnlyImage, cancellationToken)) { var version = await this.GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); // get or build compilation up to declaration state. this compilation will be used to provide live xml doc comment var declarationCompilation = await this.GetOrBuildDeclarationCompilationAsync(solution.Services, cancellationToken: cancellationToken).ConfigureAwait(false); solution.Workspace.LogTestMessage($"Looking for a cached skeleton assembly for {projectReference.ProjectId} before taking the lock..."); if (!MetadataOnlyReference.TryGetReference(solution, projectReference, declarationCompilation, version, out var reference)) { // using async build lock so we don't get multiple consumers attempting to build metadata-only images for the same compilation. using (await _buildLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { solution.Workspace.LogTestMessage($"Build lock taken for {ProjectState.Id}..."); // okay, we still don't have one. bring the compilation to final state since we are going to use it to create skeleton assembly var compilationInfo = await this.GetOrBuildCompilationInfoAsync(solution, lockGate: false, cancellationToken: cancellationToken).ConfigureAwait(false); reference = MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilationInfo.Compilation, version, cancellationToken); } } else { solution.Workspace.LogTestMessage($"Reusing the already cached skeleton assembly for {projectReference.ProjectId}"); } return reference; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with /// given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(name, filter, cancellationToken); } /// <summary> /// check whether the compilation contains any declaration symbol from syntax trees with given name /// </summary> public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // DO NOT expose declaration only compilation to outside since it can be held alive long time, we don't want to create any symbol from the declaration only compilation. var state = this.ReadState(); return state.DeclarationOnlyCompilation == null ? (bool?)null : state.DeclarationOnlyCompilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { var state = this.ReadState(); if (state.HasSuccessfullyLoaded.HasValue) { return state.HasSuccessfullyLoaded.Value ? SpecializedTasks.True : SpecializedTasks.False; } else { return HasSuccessfullyLoadedSlowAsync(solution, cancellationToken); } } private async Task<bool> HasSuccessfullyLoadedSlowAsync(SolutionState solution, CancellationToken cancellationToken) { var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.HasSuccessfullyLoaded; } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { // If we don't have any generators, then we know we have no generated files, so we can skip the computation entirely. if (!this.ProjectState.SourceGenerators.Any()) { return TextDocumentStates<SourceGeneratedDocumentState>.Empty; } var compilationInfo = await GetOrBuildCompilationInfoAsync(solution, lockGate: true, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationInfo.GeneratedDocuments; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { var state = ReadState(); // If we are in FinalState, then we have correctly ran generators and then know the final contents of the // Compilation. The GeneratedDocuments can be filled for intermediate states, but those aren't guaranteed to be // correct and can be re-ran later. return state is FinalState finalState ? finalState.GeneratedDocuments.GetState(documentId) : null; } #region Versions // Dependent Versions are stored on compilation tracker so they are more likely to survive when unrelated solution branching occurs. private AsyncLazy<VersionStamp>? _lazyDependentVersion; private AsyncLazy<VersionStamp>? _lazyDependentSemanticVersion; public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var projVersion = projectState.Version; var docVersion = await projectState.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var version = docVersion.GetNewerVersion(projVersion); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { if (_lazyDependentSemanticVersion == null) { var tmp = solution; // temp. local to avoid a closure allocation for the fast path // note: solution is captured here, but it will go away once GetValueAsync executes. Interlocked.CompareExchange(ref _lazyDependentSemanticVersion, new AsyncLazy<VersionStamp>(c => ComputeDependentSemanticVersionAsync(tmp, c), cacheResult: true), null); } return _lazyDependentSemanticVersion.GetValueAsync(cancellationToken); } private async Task<VersionStamp> ComputeDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { var projectState = this.ProjectState; var version = await projectState.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false); foreach (var dependentProjectReference in projectState.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); if (solution.ContainsProject(dependentProjectReference.ProjectId)) { var dependentProjectVersion = await solution.GetDependentSemanticVersionAsync(dependentProjectReference.ProjectId, cancellationToken).ConfigureAwait(false); version = dependentProjectVersion.GetNewerVersion(version); } } return version; } #endregion } } }
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.GeneratedFileReplacingCompilationTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// An implementation of <see cref="ICompilationTracker"/> that takes a compilation from another compilation tracker and updates it /// to return a generated document with a specific content, regardless of what the generator actually produces. In other words, it says /// "take the compilation this other thing produced, and pretend the generator gave this content, even if it wouldn't." /// </summary> private class GeneratedFileReplacingCompilationTracker : ICompilationTracker { private readonly ICompilationTracker _underlyingTracker; private readonly SourceGeneratedDocumentState _replacedGeneratedDocumentState; /// <summary> /// The lazily-produced compilation that has the generated document updated. This is initialized by call to /// <see cref="GetCompilationAsync"/>. /// </summary> [DisallowNull] private Compilation? _compilationWithReplacement; public GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) { _underlyingTracker = underlyingTracker; _replacedGeneratedDocumentState = replacementDocumentState; } public bool HasCompilation => _underlyingTracker.HasCompilation; public ProjectState ProjectState => _underlyingTracker.ProjectState; public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (_compilationWithReplacement == null) { // We don't have a compilation yet, so this couldn't have came from us return false; } else { return UnrootedSymbolSet.Create(_compilationWithReplacement).ContainsAssemblyOrModuleOrDynamic(symbol, primary); } } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { // TODO: This only needs to be implemented if a feature that operates from a source generated file then makes // further mutations to that project, which isn't needed for now. This will be need to be fixed up when we complete // https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { // Because we override SourceGeneratedDocument.WithFrozenPartialSemantics directly, we shouldn't be able to get here. throw ExceptionUtilities.Unreachable; } public async Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { // Fast path if we've definitely already done this before if (_compilationWithReplacement != null) { return _compilationWithReplacement; } var underlyingCompilation = await _underlyingTracker.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); var underlyingSourceGeneratedDocuments = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); underlyingSourceGeneratedDocuments.TryGetState(_replacedGeneratedDocumentState.Id, out var existingState); Compilation newCompilation; var newSyntaxTree = await _replacedGeneratedDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (existingState != null) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. var existingSyntaxTree = await existingState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); newCompilation = underlyingCompilation.ReplaceSyntaxTree(existingSyntaxTree, newSyntaxTree); } else { // The existing output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. newCompilation = underlyingCompilation.AddSyntaxTrees(newSyntaxTree); } Interlocked.CompareExchange(ref _compilationWithReplacement, newCompilation, null); return _compilationWithReplacement; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentSemanticVersionAsync(solution, cancellationToken); } public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentVersionAsync(solution, cancellationToken); } public async Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { var compilation = await GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); // If it's the same language we can just make a CompilationReference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { var version = await GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); return MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilation, version, cancellationToken); } } public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { // This method is used if you're forking a solution with partial semantics, and used to quickly produce references. // So this method should only be called if: // // 1. Project A has a open source generated document, and this CompilationTracker represents A // 2. Project B references that A, and is being frozen for partial semantics. // // We generally don't use partial semantics in a different project than the open file, so this isn't a scenario we need to support. throw new NotImplementedException(); } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { var underlyingGeneratedDocumentStates = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); if (underlyingGeneratedDocumentStates.Contains(_replacedGeneratedDocumentState.Id)) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. return underlyingGeneratedDocumentStates.SetState(_replacedGeneratedDocumentState.Id, _replacedGeneratedDocumentState); } else { // The generated output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(_replacedGeneratedDocumentState)); } } public IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { return _underlyingTracker.GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.HasSuccessfullyLoadedAsync(solution, cancellationToken); } public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { compilation = _compilationWithReplacement; return compilation != null; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { if (documentId == _replacedGeneratedDocumentState.Id) { return _replacedGeneratedDocumentState; } else { return _underlyingTracker.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <summary> /// An implementation of <see cref="ICompilationTracker"/> that takes a compilation from another compilation tracker and updates it /// to return a generated document with a specific content, regardless of what the generator actually produces. In other words, it says /// "take the compilation this other thing produced, and pretend the generator gave this content, even if it wouldn't." /// </summary> private class GeneratedFileReplacingCompilationTracker : ICompilationTracker { private readonly ICompilationTracker _underlyingTracker; private readonly SourceGeneratedDocumentState _replacedGeneratedDocumentState; /// <summary> /// The lazily-produced compilation that has the generated document updated. This is initialized by call to /// <see cref="GetCompilationAsync"/>. /// </summary> [DisallowNull] private Compilation? _compilationWithReplacement; public GeneratedFileReplacingCompilationTracker(ICompilationTracker underlyingTracker, SourceGeneratedDocumentState replacementDocumentState) { _underlyingTracker = underlyingTracker; _replacedGeneratedDocumentState = replacementDocumentState; } public bool HasCompilation => _underlyingTracker.HasCompilation; public ProjectState ProjectState => _underlyingTracker.ProjectState; public bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary) { if (_compilationWithReplacement == null) { // We don't have a compilation yet, so this couldn't have came from us return false; } else { return UnrootedSymbolSet.Create(_compilationWithReplacement).ContainsAssemblyOrModuleOrDynamic(symbol, primary); } } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken) { // TODO: This only needs to be implemented if a feature that operates from a source generated file needs to search for declarations // with other names; those APIs are only used by certain code fixes which isn't a need for now. This will need to be fixed up when // we complete https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default) { // TODO: This only needs to be implemented if a feature that operates from a source generated file then makes // further mutations to that project, which isn't needed for now. This will be need to be fixed up when we complete // https://github.com/dotnet/roslyn/issues/49533. throw new NotImplementedException(); } public ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken) { // Because we override SourceGeneratedDocument.WithFrozenPartialSemantics directly, we shouldn't be able to get here. throw ExceptionUtilities.Unreachable; } public async Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken) { // Fast path if we've definitely already done this before if (_compilationWithReplacement != null) { return _compilationWithReplacement; } var underlyingCompilation = await _underlyingTracker.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); var underlyingSourceGeneratedDocuments = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); underlyingSourceGeneratedDocuments.TryGetState(_replacedGeneratedDocumentState.Id, out var existingState); Compilation newCompilation; var newSyntaxTree = await _replacedGeneratedDocumentState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (existingState != null) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. var existingSyntaxTree = await existingState.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); newCompilation = underlyingCompilation.ReplaceSyntaxTree(existingSyntaxTree, newSyntaxTree); } else { // The existing output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. newCompilation = underlyingCompilation.AddSyntaxTrees(newSyntaxTree); } Interlocked.CompareExchange(ref _compilationWithReplacement, newCompilation, null); return _compilationWithReplacement; } public Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentSemanticVersionAsync(solution, cancellationToken); } public Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.GetDependentVersionAsync(solution, cancellationToken); } public async Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { var compilation = await GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); // If it's the same language we can just make a CompilationReference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { return compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes); } else { var version = await GetDependentSemanticVersionAsync(solution, cancellationToken).ConfigureAwait(false); return MetadataOnlyReference.GetOrBuildReference(solution, projectReference, compilation, version, cancellationToken); } } public CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference) { // This method is used if you're forking a solution with partial semantics, and used to quickly produce references. // So this method should only be called if: // // 1. Project A has a open source generated document, and this CompilationTracker represents A // 2. Project B references that A, and is being frozen for partial semantics. // // We generally don't use partial semantics in a different project than the open file, so this isn't a scenario we need to support. throw new NotImplementedException(); } public async ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken) { var underlyingGeneratedDocumentStates = await _underlyingTracker.GetSourceGeneratedDocumentStatesAsync(solution, cancellationToken).ConfigureAwait(false); if (underlyingGeneratedDocumentStates.Contains(_replacedGeneratedDocumentState.Id)) { // The generated file still exists in the underlying compilation, but the contents may not match the open file if the open file // is stale. Replace the syntax tree so we have a tree that matches the text. return underlyingGeneratedDocumentStates.SetState(_replacedGeneratedDocumentState.Id, _replacedGeneratedDocumentState); } else { // The generated output no longer exists in the underlying compilation. This could happen if the user made // an edit which would cause this file to no longer exist, but they're still operating on an open representation // of that file. To ensure that this snapshot is still usable, we'll just add this document back in. This is not a // semantically correct operation, but working on stale snapshots never has that guarantee. return underlyingGeneratedDocumentStates.AddRange(ImmutableArray.Create(_replacedGeneratedDocumentState)); } } public Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken) { return _underlyingTracker.HasSuccessfullyLoadedAsync(solution, cancellationToken); } public bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation) { compilation = _compilationWithReplacement; return compilation != null; } public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { if (documentId == _replacedGeneratedDocumentState.Id) { return _replacedGeneratedDocumentState; } else { return _underlyingTracker.TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } } } } }
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { /// <summary> /// Returns true if this tracker currently either points to a compilation, has an in-progress /// compilation being computed, or has a skeleton reference. Note: this is simply a weak /// statement about the tracker at this exact moment in time. Immediately after this returns /// the tracker might change and may no longer have a final compilation (for example, if the /// retainer let go of it) or might not have an in-progress compilation (for example, if the /// background compiler finished with it). /// /// Because of the above limitations, this should only be used by clients as a weak form of /// information about the tracker. For example, a client may see that a tracker has no /// compilation and may choose to throw it away knowing that it could be reconstructed at a /// later point if necessary. /// </summary> bool HasCompilation { get; } ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.CodeAnalysis; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { private interface ICompilationTracker { /// <summary> /// Returns true if this tracker currently either points to a compilation, has an in-progress /// compilation being computed, or has a skeleton reference. Note: this is simply a weak /// statement about the tracker at this exact moment in time. Immediately after this returns /// the tracker might change and may no longer have a final compilation (for example, if the /// retainer let go of it) or might not have an in-progress compilation (for example, if the /// background compiler finished with it). /// /// Because of the above limitations, this should only be used by clients as a weak form of /// information about the tracker. For example, a client may see that a tracker has no /// compilation and may choose to throw it away knowing that it could be reconstructed at a /// later point if necessary. /// </summary> bool HasCompilation { get; } ProjectState ProjectState { get; } /// <summary> /// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the /// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see /// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>. /// </summary> /// <remarks> /// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered /// when answering this question. In other words, if <paramref name="symbol"/> is an <see /// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only /// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is /// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any /// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for /// any of the references of the <see cref="Compilation.References"/>. /// </remarks> bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken); bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken); ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, CancellationToken cancellationToken = default); ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken); Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken); Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken); /// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken); CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference); ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken); Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken); bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation); SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId); } } }
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) { if (!tracker.HasCompilation) { continue; } builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); } return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } public async Task<ImmutableArray<DocumentState>> GetDocumentsWithNameAsync( ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { // this will be used to find documents that contain declaration information in IDE cache such as DeclarationSyntaxTreeInfo for "NavigateTo" var trees = GetCompilationTracker(id).GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (trees != null) { return ConvertTreesToDocuments(id, trees); } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return ImmutableArray<DocumentState>.Empty; } return ConvertTreesToDocuments( id, compilation.GetSymbolsWithName(predicate, filter, cancellationToken).SelectMany(s => s.DeclaringSyntaxReferences.Select(r => r.SyntaxTree))); } private ImmutableArray<DocumentState> ConvertTreesToDocuments(ProjectId id, IEnumerable<SyntaxTree> trees) { var result = ArrayBuilder<DocumentState>.GetInstance(); foreach (var tree in trees) { var document = GetDocumentState(tree, id); if (document == null) { // ignore trees that are not known to solution such as VB synthesized trees made by compilation. continue; } result.Add(document); } return result.ToImmutableAndFree(); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Logging; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a set of projects and their source code documents. /// /// this is a green node of Solution like ProjectState/DocumentState are for /// Project and Document. /// </summary> internal partial class SolutionState { // branch id for this solution private readonly BranchId _branchId; // the version of the workspace this solution is from private readonly int _workspaceVersion; private readonly SolutionInfo.SolutionAttributes _solutionAttributes; private readonly SolutionServices _solutionServices; private readonly ImmutableDictionary<ProjectId, ProjectState> _projectIdToProjectStateMap; private readonly ImmutableHashSet<string> _remoteSupportedLanguages; private readonly ImmutableDictionary<string, ImmutableArray<DocumentId>> _filePathToDocumentIdsMap; private readonly ProjectDependencyGraph _dependencyGraph; public readonly IReadOnlyList<AnalyzerReference> AnalyzerReferences; // Values for all these are created on demand. private ImmutableDictionary<ProjectId, ICompilationTracker> _projectIdToTrackerMap; // Checksums for this solution state private readonly ValueSource<SolutionStateChecksums> _lazyChecksums; /// <summary> /// Mapping from project-id to the options and checksums needed to synchronize it (and the projects it depends on) over /// to an OOP host. Options are stored as well so that when we are attempting to match a request for a particular project-subset /// we can return the options specific to that project-subset (which may be different from the <see cref="Options"/> defined /// for the entire solution). Lock this specific field before reading/writing to it. /// </summary> private readonly Dictionary<ProjectId, (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums)> _lazyProjectChecksums = new(); // holds on data calculated based on the AnalyzerReferences list private readonly Lazy<HostDiagnosticAnalyzers> _lazyAnalyzers; /// <summary> /// Cache we use to map between unrooted symbols (i.e. assembly, module and dynamic symbols) and the project /// they came from. That way if we are asked about many symbols from the same assembly/module we can answer the /// question quickly after computing for the first one. Created on demand. /// </summary> private ConditionalWeakTable<ISymbol, ProjectId?>? _unrootedSymbolToProjectId; private static readonly Func<ConditionalWeakTable<ISymbol, ProjectId?>> s_createTable = () => new ConditionalWeakTable<ISymbol, ProjectId?>(); private readonly SourceGeneratedDocumentState? _frozenSourceGeneratedDocumentState; private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, IReadOnlyList<ProjectId> projectIds, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableHashSet<string> remoteSupportedLanguages, ImmutableDictionary<ProjectId, ICompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> filePathToDocumentIdsMap, ProjectDependencyGraph dependencyGraph, Lazy<HostDiagnosticAnalyzers>? lazyAnalyzers, SourceGeneratedDocumentState? frozenSourceGeneratedDocument) { _branchId = branchId; _workspaceVersion = workspaceVersion; _solutionAttributes = solutionAttributes; _solutionServices = solutionServices; ProjectIds = projectIds; Options = options; AnalyzerReferences = analyzerReferences; _projectIdToProjectStateMap = idToProjectStateMap; _remoteSupportedLanguages = remoteSupportedLanguages; _projectIdToTrackerMap = projectIdToTrackerMap; _filePathToDocumentIdsMap = filePathToDocumentIdsMap; _dependencyGraph = dependencyGraph; _lazyAnalyzers = lazyAnalyzers ?? CreateLazyHostDiagnosticAnalyzers(analyzerReferences); _frozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument; // when solution state is changed, we recalculate its checksum _lazyChecksums = new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude: null, Options, c), cacheResult: true); CheckInvariants(); // make sure we don't accidentally capture any state but the list of references: static Lazy<HostDiagnosticAnalyzers> CreateLazyHostDiagnosticAnalyzers(IReadOnlyList<AnalyzerReference> analyzerReferences) => new(() => new HostDiagnosticAnalyzers(analyzerReferences)); } public SolutionState( BranchId primaryBranchId, SolutionServices solutionServices, SolutionInfo.SolutionAttributes solutionAttributes, SerializableOptionSet options, IReadOnlyList<AnalyzerReference> analyzerReferences) : this( primaryBranchId, workspaceVersion: 0, solutionServices, solutionAttributes, projectIds: SpecializedCollections.EmptyBoxedImmutableArray<ProjectId>(), options, analyzerReferences, idToProjectStateMap: ImmutableDictionary<ProjectId, ProjectState>.Empty, remoteSupportedLanguages: ImmutableHashSet<string>.Empty, projectIdToTrackerMap: ImmutableDictionary<ProjectId, ICompilationTracker>.Empty, filePathToDocumentIdsMap: ImmutableDictionary.Create<string, ImmutableArray<DocumentId>>(StringComparer.OrdinalIgnoreCase), dependencyGraph: ProjectDependencyGraph.Empty, lazyAnalyzers: null, frozenSourceGeneratedDocument: null) { } public SolutionState WithNewWorkspace(Workspace workspace, int workspaceVersion) { var services = workspace != _solutionServices.Workspace ? new SolutionServices(workspace) : _solutionServices; // Note: this will potentially have problems if the workspace services are different, as some services // get locked-in by document states and project states when first constructed. return CreatePrimarySolution(branchId: workspace.PrimaryBranchId, workspaceVersion: workspaceVersion, services: services); } public HostDiagnosticAnalyzers Analyzers => _lazyAnalyzers.Value; public SolutionInfo.SolutionAttributes SolutionAttributes => _solutionAttributes; public SourceGeneratedDocumentState? FrozenSourceGeneratedDocumentState => _frozenSourceGeneratedDocumentState; public ImmutableDictionary<ProjectId, ProjectState> ProjectStates => _projectIdToProjectStateMap; public int WorkspaceVersion => _workspaceVersion; public SolutionServices Services => _solutionServices; public SerializableOptionSet Options { get; } /// <summary> /// branch id of this solution /// /// currently, it only supports one level of branching. there is a primary branch of a workspace and all other /// branches that are branched from the primary branch. /// /// one still can create multiple forked solutions from an already branched solution, but versions among those /// can't be reliably used and compared. /// /// version only has a meaning between primary solution and branched one or between solutions from same branch. /// </summary> public BranchId BranchId => _branchId; /// <summary> /// The Workspace this solution is associated with. /// </summary> public Workspace Workspace => _solutionServices.Workspace; /// <summary> /// The Id of the solution. Multiple solution instances may share the same Id. /// </summary> public SolutionId Id => _solutionAttributes.Id; /// <summary> /// The path to the solution file or null if there is no solution file. /// </summary> public string? FilePath => _solutionAttributes.FilePath; /// <summary> /// The solution version. This equates to the solution file's version. /// </summary> public VersionStamp Version => _solutionAttributes.Version; /// <summary> /// A list of all the ids for all the projects contained by the solution. /// </summary> public IReadOnlyList<ProjectId> ProjectIds { get; } // Only run this in debug builds; even the .Any() call across all projects can be expensive when there's a lot of them. [Conditional("DEBUG")] private void CheckInvariants() { Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == ProjectIds.Count); Contract.ThrowIfFalse(_projectIdToProjectStateMap.Count == _dependencyGraph.ProjectIds.Count); // An id shouldn't point at a tracker for a different project. Contract.ThrowIfTrue(_projectIdToTrackerMap.Any(kvp => kvp.Key != kvp.Value.ProjectState.Id)); // project ids must be the same: Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(ProjectIds)); Debug.Assert(_projectIdToProjectStateMap.Keys.SetEquals(_dependencyGraph.ProjectIds)); Debug.Assert(_remoteSupportedLanguages.SetEquals(GetRemoteSupportedProjectLanguages(_projectIdToProjectStateMap))); } private SolutionState Branch( SolutionInfo.SolutionAttributes? solutionAttributes = null, IReadOnlyList<ProjectId>? projectIds = null, SerializableOptionSet? options = null, IReadOnlyList<AnalyzerReference>? analyzerReferences = null, ImmutableDictionary<ProjectId, ProjectState>? idToProjectStateMap = null, ImmutableHashSet<string>? remoteSupportedProjectLanguages = null, ImmutableDictionary<ProjectId, ICompilationTracker>? projectIdToTrackerMap = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? filePathToDocumentIdsMap = null, ProjectDependencyGraph? dependencyGraph = null, Optional<SourceGeneratedDocumentState?> frozenSourceGeneratedDocument = default) { var branchId = GetBranchId(); if (idToProjectStateMap is not null) { Contract.ThrowIfNull(remoteSupportedProjectLanguages); } solutionAttributes ??= _solutionAttributes; projectIds ??= ProjectIds; idToProjectStateMap ??= _projectIdToProjectStateMap; remoteSupportedProjectLanguages ??= _remoteSupportedLanguages; Debug.Assert(remoteSupportedProjectLanguages.SetEquals(GetRemoteSupportedProjectLanguages(idToProjectStateMap))); options ??= Options.WithLanguages(remoteSupportedProjectLanguages); analyzerReferences ??= AnalyzerReferences; projectIdToTrackerMap ??= _projectIdToTrackerMap; filePathToDocumentIdsMap ??= _filePathToDocumentIdsMap; dependencyGraph ??= _dependencyGraph; var newFrozenSourceGeneratedDocumentState = frozenSourceGeneratedDocument.HasValue ? frozenSourceGeneratedDocument.Value : _frozenSourceGeneratedDocumentState; var analyzerReferencesEqual = AnalyzerReferences.SequenceEqual(analyzerReferences); if (branchId == _branchId && solutionAttributes == _solutionAttributes && projectIds == ProjectIds && options == Options && analyzerReferencesEqual && idToProjectStateMap == _projectIdToProjectStateMap && projectIdToTrackerMap == _projectIdToTrackerMap && filePathToDocumentIdsMap == _filePathToDocumentIdsMap && dependencyGraph == _dependencyGraph && newFrozenSourceGeneratedDocumentState == _frozenSourceGeneratedDocumentState) { return this; } return new SolutionState( branchId, _workspaceVersion, _solutionServices, solutionAttributes, projectIds, options, analyzerReferences, idToProjectStateMap, remoteSupportedProjectLanguages, projectIdToTrackerMap, filePathToDocumentIdsMap, dependencyGraph, analyzerReferencesEqual ? _lazyAnalyzers : null, newFrozenSourceGeneratedDocumentState); } private SolutionState CreatePrimarySolution( BranchId branchId, int workspaceVersion, SolutionServices services) { if (branchId == _branchId && workspaceVersion == _workspaceVersion && services == _solutionServices) { return this; } return new SolutionState( branchId, workspaceVersion, services, _solutionAttributes, ProjectIds, Options, AnalyzerReferences, _projectIdToProjectStateMap, _remoteSupportedLanguages, _projectIdToTrackerMap, _filePathToDocumentIdsMap, _dependencyGraph, _lazyAnalyzers, frozenSourceGeneratedDocument: null); } private BranchId GetBranchId() { // currently we only support one level branching. // my reasonings are // 1. it seems there is no-one who needs sub branches. // 2. this lets us to branch without explicit branch API return _branchId == Workspace.PrimaryBranchId ? BranchId.GetNextId() : _branchId; } /// <summary> /// The version of the most recently modified project. /// </summary> public VersionStamp GetLatestProjectVersion() { // this may produce a version that is out of sync with the actual Document versions. var latestVersion = VersionStamp.Default; foreach (var project in this.ProjectStates.Values) { latestVersion = project.Version.GetNewerVersion(latestVersion); } return latestVersion; } /// <summary> /// True if the solution contains a project with the specified project ID. /// </summary> public bool ContainsProject([NotNullWhen(returnValue: true)] ProjectId? projectId) => projectId != null && _projectIdToProjectStateMap.ContainsKey(projectId); /// <summary> /// True if the solution contains the document in one of its projects /// </summary> public bool ContainsDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.DocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the additional document in one of its projects /// </summary> public bool ContainsAdditionalDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AdditionalDocumentStates.Contains(documentId); } /// <summary> /// True if the solution contains the analyzer config document in one of its projects /// </summary> public bool ContainsAnalyzerConfigDocument([NotNullWhen(returnValue: true)] DocumentId? documentId) { return documentId != null && this.ContainsProject(documentId.ProjectId) && this.GetProjectState(documentId.ProjectId)!.AnalyzerConfigDocumentStates.Contains(documentId); } private DocumentState GetRequiredDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).DocumentStates.GetRequiredState(documentId); private AdditionalDocumentState GetRequiredAdditionalDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AdditionalDocumentStates.GetRequiredState(documentId); private AnalyzerConfigDocumentState GetRequiredAnalyzerConfigDocumentState(DocumentId documentId) => GetRequiredProjectState(documentId.ProjectId).AnalyzerConfigDocumentStates.GetRequiredState(documentId); internal DocumentState? GetDocumentState(SyntaxTree? syntaxTree, ProjectId? projectId) { if (syntaxTree != null) { // is this tree known to be associated with a document? var documentId = DocumentState.GetDocumentIdForTree(syntaxTree); if (documentId != null && (projectId == null || documentId.ProjectId == projectId)) { // does this solution even have the document? var projectState = GetProjectState(documentId.ProjectId); if (projectState != null) { var document = projectState.DocumentStates.GetState(documentId); if (document != null) { // does this document really have the syntax tree? if (document.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return document; } } else { var generatedDocument = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); if (generatedDocument != null) { // does this document really have the syntax tree? if (generatedDocument.TryGetSyntaxTree(out var documentTree) && documentTree == syntaxTree) { return generatedDocument; } } } } } } return null; } public Task<VersionStamp> GetDependentVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentVersionAsync(this, cancellationToken); public Task<VersionStamp> GetDependentSemanticVersionAsync(ProjectId projectId, CancellationToken cancellationToken) => this.GetCompilationTracker(projectId).GetDependentSemanticVersionAsync(this, cancellationToken); public ProjectState? GetProjectState(ProjectId projectId) { _projectIdToProjectStateMap.TryGetValue(projectId, out var state); return state; } public ProjectState GetRequiredProjectState(ProjectId projectId) { var result = GetProjectState(projectId); Contract.ThrowIfNull(result); return result; } /// <summary> /// Gets the <see cref="Project"/> associated with an assembly symbol. /// </summary> public ProjectState? GetProjectState(IAssemblySymbol? assemblySymbol) { if (assemblySymbol == null) return null; s_assemblyOrModuleSymbolToProjectMap.TryGetValue(assemblySymbol, out var id); return id == null ? null : this.GetProjectState(id); } private bool TryGetCompilationTracker(ProjectId projectId, [NotNullWhen(returnValue: true)] out ICompilationTracker? tracker) => _projectIdToTrackerMap.TryGetValue(projectId, out tracker); private static readonly Func<ProjectId, SolutionState, CompilationTracker> s_createCompilationTrackerFunction = CreateCompilationTracker; private static CompilationTracker CreateCompilationTracker(ProjectId projectId, SolutionState solution) { var projectState = solution.GetProjectState(projectId); Contract.ThrowIfNull(projectState); return new CompilationTracker(projectState); } private ICompilationTracker GetCompilationTracker(ProjectId projectId) { if (!_projectIdToTrackerMap.TryGetValue(projectId, out var tracker)) { tracker = ImmutableInterlocked.GetOrAdd(ref _projectIdToTrackerMap, projectId, s_createCompilationTrackerFunction, this); } return tracker; } private SolutionState AddProject(ProjectId projectId, ProjectState projectState) { // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Add(projectId); var newStateMap = _projectIdToProjectStateMap.Add(projectId, projectState); var newLanguages = RemoteSupportedLanguages.IsSupported(projectState.Language) ? _remoteSupportedLanguages.Add(projectState.Language) : _remoteSupportedLanguages; var newDependencyGraph = _dependencyGraph .WithAdditionalProject(projectId) .WithAdditionalProjectReferences(projectId, projectState.ProjectReferences); // It's possible that another project already in newStateMap has a reference to this project that we're adding, since we allow // dangling references like that. If so, we'll need to link those in too. foreach (var newState in newStateMap) { foreach (var projectReference in newState.Value.ProjectReferences) { if (projectReference.ProjectId == projectId) { newDependencyGraph = newDependencyGraph.WithAdditionalProjectReferences( newState.Key, SpecializedCollections.SingletonReadOnlyList(projectReference)); break; } } } var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithAddedDocuments(GetDocumentStates(newStateMap[projectId])); return Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance that includes a project with the specified project information. /// </summary> public SolutionState AddProject(ProjectInfo projectInfo) { if (projectInfo == null) { throw new ArgumentNullException(nameof(projectInfo)); } var projectId = projectInfo.Id; var language = projectInfo.Language; if (language == null) { throw new ArgumentNullException(nameof(language)); } var displayName = projectInfo.Name; if (displayName == null) { throw new ArgumentNullException(nameof(displayName)); } CheckNotContainsProject(projectId); var languageServices = this.Workspace.Services.GetLanguageServices(language); if (languageServices == null) { throw new ArgumentException(string.Format(WorkspacesResources.The_language_0_is_not_supported, language)); } var newProject = new ProjectState(projectInfo, languageServices, _solutionServices); return this.AddProject(newProject.Id, newProject); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithAddedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } builder.MultiAdd(filePath, documentState.Id); } return builder.ToImmutable(); } private static IEnumerable<TextDocumentState> GetDocumentStates(ProjectState projectState) => projectState.DocumentStates.States.Values .Concat<TextDocumentState>(projectState.AdditionalDocumentStates.States.Values) .Concat(projectState.AnalyzerConfigDocumentStates.States.Values); /// <summary> /// Create a new solution instance without the project specified. /// </summary> public SolutionState RemoveProject(ProjectId projectId) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } CheckContainsProject(projectId); // changed project list so, increment version. var newSolutionAttributes = _solutionAttributes.With(version: this.Version.GetNewerVersion()); var newProjectIds = ProjectIds.ToImmutableArray().Remove(projectId); var newStateMap = _projectIdToProjectStateMap.Remove(projectId); // Remote supported languages only changes if the removed project is the last project of a supported language. var newLanguages = _remoteSupportedLanguages; if (_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) && RemoteSupportedLanguages.IsSupported(projectState.Language)) { var stillSupportsLanguage = false; foreach (var (id, state) in _projectIdToProjectStateMap) { if (id == projectId) continue; if (state.Language == projectState.Language) { stillSupportsLanguage = true; break; } } if (!stillSupportsLanguage) { newLanguages = newLanguages.Remove(projectState.Language); } } var newDependencyGraph = _dependencyGraph.WithProjectRemoved(projectId); var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithRemovedDocuments(GetDocumentStates(_projectIdToProjectStateMap[projectId])); return this.Branch( solutionAttributes: newSolutionAttributes, projectIds: newProjectIds, idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap.Remove(projectId), filePathToDocumentIdsMap: newFilePathToDocumentIdsMap, dependencyGraph: newDependencyGraph); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithRemovedDocuments(IEnumerable<TextDocumentState> documentStates) { var builder = _filePathToDocumentIdsMap.ToBuilder(); foreach (var documentState in documentStates) { var filePath = documentState.FilePath; if (RoslynString.IsNullOrEmpty(filePath)) { continue; } if (!builder.TryGetValue(filePath, out var documentIdsWithPath) || !documentIdsWithPath.Contains(documentState.Id)) { throw new ArgumentException($"The given documentId was not found in '{nameof(_filePathToDocumentIdsMap)}'."); } builder.MultiRemove(filePath, documentState.Id); } return builder.ToImmutable(); } private ImmutableDictionary<string, ImmutableArray<DocumentId>> CreateFilePathToDocumentIdsMapWithFilePath(DocumentId documentId, string? oldFilePath, string? newFilePath) { if (oldFilePath == newFilePath) { return _filePathToDocumentIdsMap; } var builder = _filePathToDocumentIdsMap.ToBuilder(); if (!RoslynString.IsNullOrEmpty(oldFilePath)) { builder.MultiRemove(oldFilePath, documentId); } if (!RoslynString.IsNullOrEmpty(newFilePath)) { builder.MultiAdd(newFilePath, documentId); } return builder.ToImmutable(); } /// <summary> /// Creates a new solution instance with the project specified updated to have the new /// assembly name. /// </summary> public SolutionState WithProjectAssemblyName(ProjectId projectId, string assemblyName) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAssemblyName(assemblyName); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectAssemblyNameAction(assemblyName)); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputFilePath(ProjectId projectId, string? outputFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputFilePath(outputFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the output file path. /// </summary> public SolutionState WithProjectOutputRefFilePath(ProjectId projectId, string? outputRefFilePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithOutputRefFilePath(outputRefFilePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the compiler output file path. /// </summary> public SolutionState WithProjectCompilationOutputInfo(ProjectId projectId, in CompilationOutputInfo info) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOutputInfo(info); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the default namespace. /// </summary> public SolutionState WithProjectDefaultNamespace(ProjectId projectId, string? defaultNamespace) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithDefaultNamespace(defaultNamespace); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the name. /// </summary> public SolutionState WithProjectName(ProjectId projectId, string name) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithName(name); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Creates a new solution instance with the project specified updated to have the project file path. /// </summary> public SolutionState WithProjectFilePath(ProjectId projectId, string? filePath) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithFilePath(filePath); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified compilation options. /// </summary> public SolutionState WithProjectCompilationOptions(ProjectId projectId, CompilationOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithCompilationOptions(options); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified parse options. /// </summary> public SolutionState WithProjectParseOptions(ProjectId projectId, ParseOptions options) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithParseOptions(options); if (oldProject == newProject) { return this; } if (Workspace.PartialSemanticsEnabled) { // don't fork tracker with queued action since access via partial semantics can become inconsistent (throw). // Since changing options is rare event, it is okay to start compilation building from scratch. return ForkProject(newProject, forkTracker: false); } else { return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: true)); } } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified hasAllInformation. /// </summary> public SolutionState WithHasAllInformation(ProjectId projectId, bool hasAllInformation) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithHasAllInformation(hasAllInformation); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to have /// the specified runAnalyzers. /// </summary> public SolutionState WithRunAnalyzers(ProjectId projectId, bool runAnalyzers) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithRunAnalyzers(runAnalyzers); if (oldProject == newProject) { return this; } // fork without any change on compilation. return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include /// the specified project references. /// </summary> public SolutionState AddProjectReferences(ProjectId projectId, IReadOnlyCollection<ProjectReference> projectReferences) { if (projectReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(projectReferences); var newProject = oldProject.WithProjectReferences(newReferences); var newDependencyGraph = _dependencyGraph.WithAdditionalProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to no longer /// include the specified project reference. /// </summary> public SolutionState RemoveProjectReference(ProjectId projectId, ProjectReference projectReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.ProjectReferences.ToImmutableArray(); // Note: uses ProjectReference equality to compare references. var newReferences = oldReferences.Remove(projectReference); if (oldReferences == newReferences) { return this; } var newProject = oldProject.WithProjectReferences(newReferences); ProjectDependencyGraph newDependencyGraph; if (newProject.ContainsReferenceToProject(projectReference.ProjectId) || !_projectIdToProjectStateMap.ContainsKey(projectReference.ProjectId)) { // Two cases: // 1) The project contained multiple non-equivalent references to the project, // and not all of them were removed. The dependency graph doesn't change. // Note that there might be two references to the same project, one with // extern alias and the other without. These are not considered duplicates. // 2) The referenced project is not part of the solution and hence not included // in the dependency graph. newDependencyGraph = _dependencyGraph; } else { newDependencyGraph = _dependencyGraph.WithProjectReferenceRemoved(projectId, projectReference.ProjectId); } return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Create a new solution instance with the project specified updated to contain /// the specified list of project references. /// </summary> public SolutionState WithProjectReferences(ProjectId projectId, IReadOnlyList<ProjectReference> projectReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithProjectReferences(projectReferences); if (oldProject == newProject) { return this; } var newDependencyGraph = _dependencyGraph.WithProjectReferences(projectId, projectReferences); return ForkProject(newProject, newDependencyGraph: newDependencyGraph); } /// <summary> /// Creates a new solution instance with the project documents in the order by the specified document ids. /// The specified document ids must be the same as what is already in the project; no adding or removing is allowed. /// </summary> public SolutionState WithProjectDocumentsOrder(ProjectId projectId, ImmutableList<DocumentId> documentIds) { var oldProject = GetRequiredProjectState(projectId); if (documentIds.Count != oldProject.DocumentStates.Count) { throw new ArgumentException($"The specified documents do not equal the project document count.", nameof(documentIds)); } foreach (var id in documentIds) { if (!oldProject.DocumentStates.Contains(id)) { throw new InvalidOperationException($"The document '{id}' does not exist in the project."); } } var newProject = oldProject.UpdateDocumentsOrder(documentIds); if (oldProject == newProject) { return this; } return ForkProject(newProject, new CompilationAndGeneratorDriverTranslationAction.ReplaceAllSyntaxTreesAction(newProject, isParseOptionChange: false)); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified metadata references. /// </summary> public SolutionState AddMetadataReferences(ProjectId projectId, IReadOnlyCollection<MetadataReference> metadataReferences) { if (metadataReferences.Count == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(metadataReferences); return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified metadata reference. /// </summary> public SolutionState RemoveMetadataReference(ProjectId projectId, MetadataReference metadataReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.MetadataReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(metadataReference); if (oldReferences == newReferences) { return this; } return ForkProject(oldProject.WithMetadataReferences(newReferences)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified metadata references. /// </summary> public SolutionState WithProjectMetadataReferences(ProjectId projectId, IReadOnlyList<MetadataReference> metadataReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithMetadataReferences(metadataReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the project specified updated to include the /// specified analyzer references. /// </summary> public SolutionState AddAnalyzerReferences(ProjectId projectId, ImmutableArray<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Length == 0) { return this; } var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.AddAnalyzerReferencesAction(analyzerReferences, oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to no longer include /// the specified analyzer reference. /// </summary> public SolutionState RemoveAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) { var oldProject = GetRequiredProjectState(projectId); var oldReferences = oldProject.AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return ForkProject( oldProject.WithAnalyzerReferences(newReferences), new CompilationAndGeneratorDriverTranslationAction.RemoveAnalyzerReferencesAction(ImmutableArray.Create(analyzerReference), oldProject.Language)); } /// <summary> /// Create a new solution instance with the project specified updated to include only the /// specified analyzer references. /// </summary> public SolutionState WithProjectAnalyzerReferences(ProjectId projectId, IEnumerable<AnalyzerReference> analyzerReferences) { var oldProject = GetRequiredProjectState(projectId); var newProject = oldProject.WithAnalyzerReferences(analyzerReferences); if (oldProject == newProject) { return this; } return ForkProject(newProject); } /// <summary> /// Create a new solution instance with the corresponding projects updated to include new /// documents defined by the document info. /// </summary> public SolutionState AddDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => project.CreateDocument(documentInfo, project.ParseOptions), (oldProject, documents) => (oldProject.AddDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddDocumentsAction(documents))); } /// <summary> /// Core helper that takes a set of <see cref="DocumentInfo" />s and does the application of the appropriate documents to each project. /// </summary> /// <param name="documentInfos">The set of documents to add.</param> /// <param name="addDocumentsToProjectState">Returns the new <see cref="ProjectState"/> with the documents added, and the <see cref="CompilationAndGeneratorDriverTranslationAction"/> needed as well.</param> /// <returns></returns> private SolutionState AddDocumentsToMultipleProjects<T>( ImmutableArray<DocumentInfo> documentInfos, Func<DocumentInfo, ProjectState, T> createDocumentState, Func<ProjectState, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> addDocumentsToProjectState) where T : TextDocumentState { if (documentInfos.IsDefault) { throw new ArgumentNullException(nameof(documentInfos)); } if (documentInfos.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentInfosByProjectId = documentInfos.ToLookup(d => d.Id.ProjectId); var newSolutionState = this; foreach (var documentInfosInProject in documentInfosByProjectId) { CheckContainsProject(documentInfosInProject.Key); var oldProjectState = this.GetProjectState(documentInfosInProject.Key)!; var newDocumentStatesForProjectBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentInfo in documentInfosInProject) { newDocumentStatesForProjectBuilder.Add(createDocumentState(documentInfo, oldProjectState)); } var newDocumentStatesForProject = newDocumentStatesForProjectBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = addDocumentsToProjectState(oldProjectState, newDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithAddedDocuments(newDocumentStatesForProject)); } return newSolutionState; } public SolutionState AddAdditionalDocuments(ImmutableArray<DocumentInfo> documentInfos) { return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AdditionalDocumentState(documentInfo, _solutionServices), (projectState, documents) => (projectState.AddAdditionalDocuments(documents), new CompilationAndGeneratorDriverTranslationAction.AddAdditionalDocumentsAction(documents))); } public SolutionState AddAnalyzerConfigDocuments(ImmutableArray<DocumentInfo> documentInfos) { // Adding a new analyzer config potentially modifies the compilation options return AddDocumentsToMultipleProjects(documentInfos, (documentInfo, project) => new AnalyzerConfigDocumentState(documentInfo, _solutionServices), (oldProject, documents) => { var newProject = oldProject.AddAnalyzerConfigDocuments(documents); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } public SolutionState RemoveAnalyzerConfigDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AnalyzerConfigDocumentStates.GetRequiredState(documentId), (oldProject, documentIds, _) => { var newProject = oldProject.RemoveAnalyzerConfigDocuments(documentIds); return (newProject, new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true)); }); } /// <summary> /// Creates a new solution instance that no longer includes the specified document. /// </summary> public SolutionState RemoveDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.DocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveDocumentsAction(documentStates))); } private SolutionState RemoveDocumentsFromMultipleProjects<T>( ImmutableArray<DocumentId> documentIds, Func<ProjectState, DocumentId, T> getExistingTextDocumentState, Func<ProjectState, ImmutableArray<DocumentId>, ImmutableArray<T>, (ProjectState newState, CompilationAndGeneratorDriverTranslationAction translationAction)> removeDocumentsFromProjectState) where T : TextDocumentState { if (documentIds.IsEmpty) { return this; } // The documents might be contributing to multiple different projects; split them by project and then we'll process // project-at-a-time. var documentIdsByProjectId = documentIds.ToLookup(id => id.ProjectId); var newSolutionState = this; foreach (var documentIdsInProject in documentIdsByProjectId) { var oldProjectState = this.GetProjectState(documentIdsInProject.Key); if (oldProjectState == null) { throw new InvalidOperationException(string.Format(WorkspacesResources._0_is_not_part_of_the_workspace, documentIdsInProject.Key)); } var removedDocumentStatesBuilder = ArrayBuilder<T>.GetInstance(); foreach (var documentId in documentIdsInProject) { removedDocumentStatesBuilder.Add(getExistingTextDocumentState(oldProjectState, documentId)); } var removedDocumentStatesForProject = removedDocumentStatesBuilder.ToImmutableAndFree(); var (newProjectState, compilationTranslationAction) = removeDocumentsFromProjectState(oldProjectState, documentIdsInProject.ToImmutableArray(), removedDocumentStatesForProject); newSolutionState = newSolutionState.ForkProject(newProjectState, compilationTranslationAction, newFilePathToDocumentIdsMap: CreateFilePathToDocumentIdsMapWithRemovedDocuments(removedDocumentStatesForProject)); } return newSolutionState; } /// <summary> /// Creates a new solution instance that no longer includes the specified additional documents. /// </summary> public SolutionState RemoveAdditionalDocuments(ImmutableArray<DocumentId> documentIds) { return RemoveDocumentsFromMultipleProjects(documentIds, (projectState, documentId) => projectState.AdditionalDocumentStates.GetRequiredState(documentId), (projectState, documentIds, documentStates) => (projectState.RemoveAdditionalDocuments(documentIds), new CompilationAndGeneratorDriverTranslationAction.RemoveAdditionalDocumentsAction(documentStates))); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified name. /// </summary> public SolutionState WithDocumentName(DocumentId documentId, string name) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Attributes.Name == name) { return this; } return UpdateDocumentState(oldDocument.UpdateName(name)); } /// <summary> /// Creates a new solution instance with the document specified updated to be contained in /// the sequence of logical folders. /// </summary> public SolutionState WithDocumentFolders(DocumentId documentId, IReadOnlyList<string> folders) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.Folders.SequenceEqual(folders)) { return this; } return UpdateDocumentState(oldDocument.UpdateFolders(folders)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the specified file path. /// </summary> public SolutionState WithDocumentFilePath(DocumentId documentId, string? filePath) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.FilePath == filePath) { return this; } return UpdateDocumentState(oldDocument.UpdateFilePath(filePath)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(text, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, SourceText text, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetText(out var oldText) && text == oldText) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(text, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAdditionalDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAdditionalDocumentState(oldDocument.UpdateText(textAndVersion, mode), textChanged: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// and version specified. /// </summary> public SolutionState WithAnalyzerConfigDocumentText(DocumentId documentId, TextAndVersion textAndVersion, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); if (oldDocument.TryGetTextAndVersion(out var oldTextAndVersion) && textAndVersion == oldTextAndVersion) { return this; } return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(textAndVersion, mode)); } /// <summary> /// Creates a new solution instance with the document specified updated to have a syntax tree /// rooted by the specified syntax node. /// </summary> public SolutionState WithDocumentSyntaxRoot(DocumentId documentId, SyntaxNode root, PreservationMode mode = PreservationMode.PreserveValue) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.TryGetSyntaxTree(out var oldTree) && oldTree.TryGetRoot(out var oldRoot) && oldRoot == root) { return this; } return UpdateDocumentState(oldDocument.UpdateTree(root, mode), textChanged: true); } private static async Task<Compilation> UpdateDocumentInCompilationAsync( Compilation compilation, DocumentState oldDocument, DocumentState newDocument, CancellationToken cancellationToken) { return compilation.ReplaceSyntaxTree( await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false), await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false)); } /// <summary> /// Creates a new solution instance with the document specified updated to have the source /// code kind specified. /// </summary> public SolutionState WithDocumentSourceCodeKind(DocumentId documentId, SourceCodeKind sourceCodeKind) { var oldDocument = GetRequiredDocumentState(documentId); if (oldDocument.SourceCodeKind == sourceCodeKind) { return this; } return UpdateDocumentState(oldDocument.UpdateSourceCodeKind(sourceCodeKind), textChanged: true); } public SolutionState UpdateDocumentTextLoader(DocumentId documentId, TextLoader loader, SourceText? text, PreservationMode mode) { var oldDocument = GetRequiredDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateDocumentState(oldDocument.UpdateText(loader, text, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the additional document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAdditionalDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAdditionalDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAdditionalDocumentState(oldDocument.UpdateText(loader, mode), textChanged: true, recalculateDependentVersions: true); } /// <summary> /// Creates a new solution instance with the analyzer config document specified updated to have the text /// supplied by the text loader. /// </summary> public SolutionState UpdateAnalyzerConfigDocumentTextLoader(DocumentId documentId, TextLoader loader, PreservationMode mode) { var oldDocument = GetRequiredAnalyzerConfigDocumentState(documentId); // Assumes that text has changed. User could have closed a doc without saving and we are loading text from closed file with // old content. Also this should make sure we don't re-use latest doc version with data associated with opened document. return UpdateAnalyzerConfigDocumentState(oldDocument.UpdateText(loader, mode)); } private SolutionState UpdateDocumentState(DocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.DocumentStates.GetRequiredState(newDocument.Id); var newFilePathToDocumentIdsMap = CreateFilePathToDocumentIdsMapWithFilePath(newDocument.Id, oldDocument.FilePath, newDocument.FilePath); return ForkProject( newProject, new CompilationAndGeneratorDriverTranslationAction.TouchDocumentAction(oldDocument, newDocument), newFilePathToDocumentIdsMap: newFilePathToDocumentIdsMap); } private SolutionState UpdateAdditionalDocumentState(AdditionalDocumentState newDocument, bool textChanged = false, bool recalculateDependentVersions = false) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAdditionalDocument(newDocument, textChanged, recalculateDependentVersions); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); var oldDocument = oldProject.AdditionalDocumentStates.GetRequiredState(newDocument.Id); return ForkProject( newProject, translate: new CompilationAndGeneratorDriverTranslationAction.TouchAdditionalDocumentAction(oldDocument, newDocument)); } private SolutionState UpdateAnalyzerConfigDocumentState(AnalyzerConfigDocumentState newDocument) { var oldProject = GetProjectState(newDocument.Id.ProjectId)!; var newProject = oldProject.UpdateAnalyzerConfigDocument(newDocument); // This method shouldn't have been called if the document has not changed. Debug.Assert(oldProject != newProject); return ForkProject(newProject, newProject.CompilationOptions != null ? new CompilationAndGeneratorDriverTranslationAction.ProjectCompilationOptionsAction(newProject, isAnalyzerConfigChange: true) : null); } /// <summary> /// Creates a new snapshot with an updated project and an action that will produce a new /// compilation matching the new project out of an old compilation. All dependent projects /// are fixed-up if the change to the new project affects its public metadata, and old /// dependent compilations are forgotten. /// </summary> private SolutionState ForkProject( ProjectState newProjectState, CompilationAndGeneratorDriverTranslationAction? translate = null, ProjectDependencyGraph? newDependencyGraph = null, ImmutableDictionary<string, ImmutableArray<DocumentId>>? newFilePathToDocumentIdsMap = null, bool forkTracker = true) { var projectId = newProjectState.Id; var newStateMap = _projectIdToProjectStateMap.SetItem(projectId, newProjectState); // Remote supported languages can only change if the project changes language. This is an unexpected edge // case, so it's not optimized for incremental updates. var newLanguages = !_projectIdToProjectStateMap.TryGetValue(projectId, out var projectState) || projectState.Language != newProjectState.Language ? GetRemoteSupportedProjectLanguages(newStateMap) : _remoteSupportedLanguages; newDependencyGraph ??= _dependencyGraph; var newTrackerMap = CreateCompilationTrackerMap(projectId, newDependencyGraph); // If we have a tracker for this project, then fork it as well (along with the // translation action and store it in the tracker map. if (newTrackerMap.TryGetValue(projectId, out var tracker)) { newTrackerMap = newTrackerMap.Remove(projectId); if (forkTracker) { newTrackerMap = newTrackerMap.Add(projectId, tracker.Fork(newProjectState, translate)); } } return this.Branch( idToProjectStateMap: newStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newTrackerMap, dependencyGraph: newDependencyGraph, filePathToDocumentIdsMap: newFilePathToDocumentIdsMap ?? _filePathToDocumentIdsMap); } /// <summary> /// Gets the set of <see cref="DocumentId"/>s in this <see cref="Solution"/> with a /// <see cref="TextDocument.FilePath"/> that matches the given file path. /// </summary> public ImmutableArray<DocumentId> GetDocumentIdsWithFilePath(string? filePath) { if (string.IsNullOrEmpty(filePath)) { return ImmutableArray<DocumentId>.Empty; } return _filePathToDocumentIdsMap.TryGetValue(filePath!, out var documentIds) ? documentIds : ImmutableArray<DocumentId>.Empty; } private static ProjectDependencyGraph CreateDependencyGraph( IReadOnlyList<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> projectStates) { var map = projectStates.Values.Select(state => new KeyValuePair<ProjectId, ImmutableHashSet<ProjectId>>( state.Id, state.ProjectReferences.Where(pr => projectStates.ContainsKey(pr.ProjectId)).Select(pr => pr.ProjectId).ToImmutableHashSet())) .ToImmutableDictionary(); return new ProjectDependencyGraph(projectIds.ToImmutableHashSet(), map); } private ImmutableDictionary<ProjectId, ICompilationTracker> CreateCompilationTrackerMap(ProjectId changedProjectId, ProjectDependencyGraph dependencyGraph) { var builder = ImmutableDictionary.CreateBuilder<ProjectId, ICompilationTracker>(); IEnumerable<ProjectId>? dependencies = null; foreach (var (id, tracker) in _projectIdToTrackerMap) { if (!tracker.HasCompilation) { continue; } builder.Add(id, CanReuse(id) ? tracker : tracker.Fork(tracker.ProjectState)); } return builder.ToImmutable(); // Returns true if 'tracker' can be reused for project 'id' bool CanReuse(ProjectId id) { if (id == changedProjectId) { return true; } // Check the dependency graph to see if project 'id' directly or transitively depends on 'projectId'. // If the information is not available, do not compute it. var forwardDependencies = dependencyGraph.TryGetProjectsThatThisProjectTransitivelyDependsOn(id); if (forwardDependencies is object && !forwardDependencies.Contains(changedProjectId)) { return true; } // Compute the set of all projects that depend on 'projectId'. This information answers the same // question as the previous check, but involves at most one transitive computation within the // dependency graph. dependencies ??= dependencyGraph.GetProjectsThatTransitivelyDependOnThisProject(changedProjectId); return !dependencies.Contains(id); } } public SolutionState WithOptions(SerializableOptionSet options) => Branch(options: options); public SolutionState AddAnalyzerReferences(IReadOnlyCollection<AnalyzerReference> analyzerReferences) { if (analyzerReferences.Count == 0) { return this; } var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.AddRange(analyzerReferences); return Branch(analyzerReferences: newReferences); } public SolutionState RemoveAnalyzerReference(AnalyzerReference analyzerReference) { var oldReferences = AnalyzerReferences.ToImmutableArray(); var newReferences = oldReferences.Remove(analyzerReference); if (oldReferences == newReferences) { return this; } return Branch(analyzerReferences: newReferences); } public SolutionState WithAnalyzerReferences(IReadOnlyList<AnalyzerReference> analyzerReferences) { if (analyzerReferences == AnalyzerReferences) { return this; } return Branch(analyzerReferences: analyzerReferences); } // this lock guards all the mutable fields (do not share lock with derived classes) private NonReentrantLock? _stateLockBackingField; private NonReentrantLock StateLock { get { // TODO: why did I need to do a nullable suppression here? return LazyInitializer.EnsureInitialized(ref _stateLockBackingField, NonReentrantLock.Factory)!; } } private WeakReference<SolutionState>? _latestSolutionWithPartialCompilation; private DateTime _timeOfLatestSolutionWithPartialCompilation; private DocumentId? _documentIdOfLatestSolutionWithPartialCompilation; /// <summary> /// Creates a branch of the solution that has its compilations frozen in whatever state they are in at the time, assuming a background compiler is /// busy building this compilations. /// /// A compilation for the project containing the specified document id will be guaranteed to exist with at least the syntax tree for the document. /// /// This not intended to be the public API, use Document.WithFrozenPartialSemantics() instead. /// </summary> public SolutionState WithFrozenPartialCompilationIncludingSpecificDocument(DocumentId documentId, CancellationToken cancellationToken) { try { var doc = this.GetRequiredDocumentState(documentId); var tree = doc.GetSyntaxTree(cancellationToken); using (this.StateLock.DisposableWait(cancellationToken)) { // in progress solutions are disabled for some testing if (this.Workspace is Workspace ws && ws.TestHookPartialSolutionsDisabled) { return this; } SolutionState? currentPartialSolution = null; if (_latestSolutionWithPartialCompilation != null) { _latestSolutionWithPartialCompilation.TryGetTarget(out currentPartialSolution); } var reuseExistingPartialSolution = currentPartialSolution != null && (DateTime.UtcNow - _timeOfLatestSolutionWithPartialCompilation).TotalSeconds < 0.1 && _documentIdOfLatestSolutionWithPartialCompilation == documentId; if (reuseExistingPartialSolution) { SolutionLogger.UseExistingPartialSolution(); return currentPartialSolution!; } // if we don't have one or it is stale, create a new partial solution var tracker = this.GetCompilationTracker(documentId.ProjectId); var newTracker = tracker.FreezePartialStateWithTree(this, doc, tree, cancellationToken); var newIdToProjectStateMap = _projectIdToProjectStateMap.SetItem(documentId.ProjectId, newTracker.ProjectState); var newLanguages = _remoteSupportedLanguages; var newIdToTrackerMap = _projectIdToTrackerMap.SetItem(documentId.ProjectId, newTracker); currentPartialSolution = this.Branch( idToProjectStateMap: newIdToProjectStateMap, remoteSupportedProjectLanguages: newLanguages, projectIdToTrackerMap: newIdToTrackerMap, dependencyGraph: CreateDependencyGraph(ProjectIds, newIdToProjectStateMap)); _latestSolutionWithPartialCompilation = new WeakReference<SolutionState>(currentPartialSolution); _timeOfLatestSolutionWithPartialCompilation = DateTime.UtcNow; _documentIdOfLatestSolutionWithPartialCompilation = documentId; SolutionLogger.CreatePartialSolution(); return currentPartialSolution; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new solution instance with all the documents specified updated to have the same specified text. /// </summary> public SolutionState WithDocumentText(IEnumerable<DocumentId?> documentIds, SourceText text, PreservationMode mode) { var solution = this; foreach (var documentId in documentIds) { if (documentId == null) { continue; } var doc = GetProjectState(documentId.ProjectId)?.DocumentStates.GetState(documentId); if (doc != null) { if (!doc.TryGetText(out var existingText) || existingText != text) { solution = solution.WithDocumentText(documentId, text, mode); } } } return solution; } public bool TryGetCompilation(ProjectId projectId, [NotNullWhen(returnValue: true)] out Compilation? compilation) { CheckContainsProject(projectId); compilation = null; return this.TryGetCompilationTracker(projectId, out var tracker) && tracker.TryGetCompilation(out compilation); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectId"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> private Task<Compilation?> GetCompilationAsync(ProjectId projectId, CancellationToken cancellationToken) { // TODO: figure out where this is called and why the nullable suppression is required return GetCompilationAsync(GetProjectState(projectId)!, cancellationToken); } /// <summary> /// Returns the compilation for the specified <see cref="ProjectState"/>. Can return <see langword="null"/> when the project /// does not support compilations. /// </summary> /// <remarks> /// The compilation is guaranteed to have a syntax tree for each document of the project. /// </remarks> public Task<Compilation?> GetCompilationAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetCompilationAsync(this, cancellationToken).AsNullable() : SpecializedTasks.Null<Compilation>(); } /// <summary> /// Return reference completeness for the given project and all projects this references. /// </summary> public Task<bool> HasSuccessfullyLoadedAsync(ProjectState project, CancellationToken cancellationToken) { // return HasAllInformation when compilation is not supported. // regardless whether project support compilation or not, if projectInfo is not complete, we can't guarantee its reference completeness return project.SupportsCompilation ? this.GetCompilationTracker(project.Id).HasSuccessfullyLoadedAsync(this, cancellationToken) : project.HasAllInformation ? SpecializedTasks.True : SpecializedTasks.False; } /// <summary> /// Returns the generated document states for source generated documents. /// </summary> public ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(ProjectState project, CancellationToken cancellationToken) { return project.SupportsCompilation ? GetCompilationTracker(project.Id).GetSourceGeneratedDocumentStatesAsync(this, cancellationToken) : new(TextDocumentStates<SourceGeneratedDocumentState>.Empty); } /// <summary> /// Returns the <see cref="SourceGeneratedDocumentState"/> for a source generated document that has already been generated and observed. /// </summary> /// <remarks> /// This is only safe to call if you already have seen the SyntaxTree or equivalent that indicates the document state has already been /// generated. This method exists to implement <see cref="Solution.GetDocument(SyntaxTree?)"/> and is best avoided unless you're doing something /// similarly tricky like that. /// </remarks> public SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId) { return GetCompilationTracker(documentId.ProjectId).TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentId); } /// <summary> /// Returns a new SolutionState that will always produce a specific output for a generated file. This is used only in the /// implementation of <see cref="TextExtensions.GetOpenDocumentInCurrentContextWithChanges"/> where if a user has a source /// generated file open, we need to make sure everything lines up. /// </summary> public SolutionState WithFrozenSourceGeneratedDocument(SourceGeneratedDocumentIdentity documentIdentity, SourceText sourceText) { // We won't support freezing multiple source generated documents at once. Although nothing in the implementation // of this method would have problems, this simplifies the handling of serializing this solution to out-of-proc. // Since we only produce these snapshots from an open document, there should be no way to observe this, so this assertion // also serves as a good check on the system. If down the road we need to support this, we can remove this check and // update the out-of-process serialization logic accordingly. Contract.ThrowIfTrue(_frozenSourceGeneratedDocumentState != null, "We shouldn't be calling WithFrozenSourceGeneratedDocument on a solution with a frozen source generated document."); var existingGeneratedState = TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(documentIdentity.DocumentId); SourceGeneratedDocumentState newGeneratedState; if (existingGeneratedState != null) { newGeneratedState = existingGeneratedState.WithUpdatedGeneratedContent(sourceText, existingGeneratedState.ParseOptions); // If the content already matched, we can just reuse the existing state if (newGeneratedState == existingGeneratedState) { return this; } } else { var projectState = GetRequiredProjectState(documentIdentity.DocumentId.ProjectId); newGeneratedState = SourceGeneratedDocumentState.Create( documentIdentity, sourceText, projectState.ParseOptions!, projectState.LanguageServices, _solutionServices); } var projectId = documentIdentity.DocumentId.ProjectId; var newTrackerMap = CreateCompilationTrackerMap(projectId, _dependencyGraph); // We want to create a new snapshot with a new compilation tracker that will do this replacement. // If we already have an existing tracker we'll just wrap that (so we also are reusing any underlying // computations). If we don't have one, we'll create one and then wrap it. if (!newTrackerMap.TryGetValue(projectId, out var existingTracker)) { existingTracker = CreateCompilationTracker(projectId, this); } newTrackerMap = newTrackerMap.SetItem( projectId, new GeneratedFileReplacingCompilationTracker(existingTracker, newGeneratedState)); return this.Branch( projectIdToTrackerMap: newTrackerMap, frozenSourceGeneratedDocument: newGeneratedState); } /// <summary> /// Symbols need to be either <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/>. /// </summary> private static readonly ConditionalWeakTable<ISymbol, ProjectId> s_assemblyOrModuleSymbolToProjectMap = new(); /// <summary> /// Get a metadata reference for the project's compilation /// </summary> public Task<MetadataReference> GetMetadataReferenceAsync(ProjectReference projectReference, ProjectState fromProject, CancellationToken cancellationToken) { try { // Get the compilation state for this project. If it's not already created, then this // will create it. Then force that state to completion and get a metadata reference to it. var tracker = this.GetCompilationTracker(projectReference.ProjectId); return tracker.GetMetadataReferenceAsync(this, fromProject, projectReference, cancellationToken); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Attempt to get the best readily available compilation for the project. It may be a /// partially built compilation. /// </summary> private MetadataReference? GetPartialMetadataReference( ProjectReference projectReference, ProjectState fromProject) { // Try to get the compilation state for this project. If it doesn't exist, don't do any // more work. if (!_projectIdToTrackerMap.TryGetValue(projectReference.ProjectId, out var state)) { return null; } return state.GetPartialMetadataReference(fromProject, projectReference); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, string name, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(name, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(name, filter, cancellationToken); } public async Task<bool> ContainsSymbolsWithNameAsync(ProjectId id, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken) { var result = GetCompilationTracker(id).ContainsSymbolsWithNameFromDeclarationOnlyCompilation(predicate, filter, cancellationToken); if (result.HasValue) { return result.Value; } // it looks like declaration compilation doesn't exist yet. we have to build full compilation var compilation = await GetCompilationAsync(id, cancellationToken).ConfigureAwait(false); if (compilation == null) { // some projects don't support compilations (e.g., TypeScript) so there's nothing to check return false; } return compilation.ContainsSymbolsWithName(predicate, filter, cancellationToken); } /// <summary> /// Gets a <see cref="ProjectDependencyGraph"/> that details the dependencies between projects for this solution. /// </summary> public ProjectDependencyGraph GetProjectDependencyGraph() => _dependencyGraph; private void CheckNotContainsProject(ProjectId projectId) { if (this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_already_contains_the_specified_project); } } private void CheckContainsProject(ProjectId projectId) { if (!this.ContainsProject(projectId)) { throw new InvalidOperationException(WorkspacesResources.The_solution_does_not_contain_the_specified_project); } } internal bool ContainsProjectReference(ProjectId projectId, ProjectReference projectReference) => GetRequiredProjectState(projectId).ProjectReferences.Contains(projectReference); internal bool ContainsMetadataReference(ProjectId projectId, MetadataReference metadataReference) => GetRequiredProjectState(projectId).MetadataReferences.Contains(metadataReference); internal bool ContainsAnalyzerReference(ProjectId projectId, AnalyzerReference analyzerReference) => GetRequiredProjectState(projectId).AnalyzerReferences.Contains(analyzerReference); internal bool ContainsTransitiveReference(ProjectId fromProjectId, ProjectId toProjectId) => _dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(fromProjectId).Contains(toProjectId); internal ImmutableHashSet<string> GetRemoteSupportedProjectLanguages() => _remoteSupportedLanguages; private static ImmutableHashSet<string> GetRemoteSupportedProjectLanguages(ImmutableDictionary<ProjectId, ProjectState> projectStates) { var builder = ImmutableHashSet.CreateBuilder<string>(); foreach (var projectState in projectStates) { if (RemoteSupportedLanguages.IsSupported(projectState.Value.Language)) { builder.Add(projectState.Value.Language); } } return builder.ToImmutable(); } } }
1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Test/Core/Assert/EqualityUnit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 Roslyn.Test.Utilities { public static class EqualityUnit { public static EqualityUnit<T> Create<T>(T value) { return new EqualityUnit<T>(value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Roslyn.Test.Utilities { public static class EqualityUnit { public static EqualityUnit<T> Create<T>(T value) { return new EqualityUnit<T>(value); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.TextChangedEventSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class TextChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public TextChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.Changed += OnTextBufferChanged; public override void Disconnect() => _subjectBuffer.Changed -= OnTextBufferChanged; private void OnTextBufferChanged(object? sender, TextContentChangedEventArgs e) { if (e.Changes.Count == 0) return; this.RaiseChanged(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class TextChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public TextChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.Changed += OnTextBufferChanged; public override void Disconnect() => _subjectBuffer.Changed -= OnTextBufferChanged; private void OnTextBufferChanged(object? sender, TextContentChangedEventArgs e) { if (e.Changes.Count == 0) return; this.RaiseChanged(); } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Analyzers/VisualBasic/CodeFixes/RemoveUnnecessaryCast/VisualBasicRemoveUnnecessaryCastCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryCast <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryCast), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateEndConstruct)> Partial Friend Class VisualBasicRemoveUnnecessaryCastCodeFixProvider Inherits SyntaxEditorBasedCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId) Friend NotOverridable Overrides ReadOnly Property CodeFixCategory As CodeFixCategory Get Return CodeFixCategory.CodeStyle End Get End Property Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task context.RegisterCodeFix(New MyCodeAction( Function(c) FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics) Return Task.CompletedTask End Function Private Shared Function IsUnnecessaryCast(node As ExpressionSyntax, model As SemanticModel, cancellationToken As CancellationToken) As Boolean Dim castExpression = TryCast(node, CastExpressionSyntax) If castExpression IsNot Nothing Then Return castExpression.IsUnnecessaryCast(model, assumeCallKeyword:=True, cancellationToken:=cancellationToken) End If Dim predefinedCastExpression = TryCast(node, PredefinedCastExpressionSyntax) If predefinedCastExpression IsNot Nothing Then Return predefinedCastExpression.IsUnnecessaryCast(model, assumeCallKeyword:=True, cancellationToken:=cancellationToken) End If Return False End Function Protected Overrides Async Function FixAllAsync( document As Document, diagnostics As ImmutableArray(Of Diagnostic), editor As SyntaxEditor, cancellationToken As CancellationToken) As Task ' VB parsing is extremely hairy. Unlike C#, it can be very dangerous to go and remove a ' cast. For example, if the cast is at the statement level, it may contain an ' expression that itself is not legal on its own at the top level (see below for an ' example of this). Similarly, removing the cast may make VB parse following code ' differently. ' ' In order to deal with all these concerns safely, we first complexify the surrounding ' statements containing the casts we want to remove. *Then* we remove the casts from ' inside that. ' ' As an example, consider: DirectCast(New Goo(), IGoo).Blah() This is ' legal code, but this is not: New Goo().Blah() ' ' (because 'new' cannot start a statement). ' So we need to instead generate: Call New Goo().Blah() Dim originalCastNodes = diagnostics.SelectAsArray( Function(d) DirectCast(d.AdditionalLocations(0).FindNode(getInnermostNodeForTie:=True, cancellationToken), ExpressionSyntax)) ' Keep track of the all the casts we want to fix up. We'll fix them up at the end ' after we've done all other manipulation. Dim trackedRoot = editor.OriginalRoot.TrackNodes(originalCastNodes) Dim trackedDocument = document.WithSyntaxRoot(trackedRoot) ' Now, go and expand all the containing statements of the nodes we want to edit. ' This is necessary to ensure that the code remains parseable and preserves semantics. Dim expandedRoot = Await ExpandSurroundingStatementsAsync(trackedDocument, originalCastNodes, cancellationToken).ConfigureAwait(False) Dim expandedDocument = document.WithSyntaxRoot(expandedRoot) Dim removedRoot = Await RemoveCastsAsync( expandedDocument, originalCastNodes, cancellationToken).ConfigureAwait(False) editor.ReplaceNode(editor.OriginalRoot, removedRoot) End Function Private Shared Async Function RemoveCastsAsync( document As Document, originalCastNodes As ImmutableArray(Of ExpressionSyntax), cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) ' Now, find the cast nodes again in the expanded document Dim currentCastNodes = root.GetCurrentNodes(originalCastNodes) Dim innerEditor = New SyntaxEditor(root, document.Project.Solution.Workspace) Await innerEditor.ApplyExpressionLevelSemanticEditsAsync( document, currentCastNodes.ToImmutableArray(), Function(semanticModel, castExpression) IsUnnecessaryCast(castExpression, semanticModel, cancellationToken), Function(unused, currentRoot, castExpression) Dim newCastExpression = Uncast(castExpression).WithAdditionalAnnotations(Formatter.Annotation) Return currentRoot.ReplaceNode(castExpression, newCastExpression) End Function, cancellationToken).ConfigureAwait(False) Return innerEditor.GetChangedRoot() End Function Private Shared Async Function ExpandSurroundingStatementsAsync( document As Document, originalNodes As ImmutableArray(Of ExpressionSyntax), cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) ' Note: we not only get the containing statement, but also the next statement after ' that. That's because the removal of the parens in the cast may then cause parsing ' problems with VB consuming the following line into the current line. This is most ' common with query clauses. By complexifying the next statement, we prevent that from ' happening. Dim trackedNodes = root.GetCurrentNodes(originalNodes) Dim containingAndNextStatements = trackedNodes.SelectMany( Function(n) Dim containingStatement = n.GetAncestorOrThis(Of StatementSyntax) Dim nextStatement = containingStatement.GetNextStatement() Return If(nextStatement Is Nothing, {containingStatement}, {containingStatement, nextStatement}) End Function).Distinct() Dim workspace = document.Project.Solution.Workspace Dim editor = New SyntaxEditor(root, workspace) For Each containingStatement In containingAndNextStatements Dim expandedStatement = Simplifier.Expand( containingStatement, semanticModel, workspace, cancellationToken:=cancellationToken) editor.ReplaceNode(containingStatement, expandedStatement) Next Return editor.GetChangedRoot() End Function Private Shared Function Uncast(old As ExpressionSyntax) As ExpressionSyntax ' parenthesize the uncasted value to help ensure any proper parsing. The excess ' parens will be removed if unnecessary. Dim castExpression = TryCast(old, CastExpressionSyntax) If castExpression IsNot Nothing Then Return castExpression.Uncast().Parenthesize() End If Dim predefinedCastExpression = TryCast(old, PredefinedCastExpressionSyntax) If predefinedCastExpression IsNot Nothing Then Return predefinedCastExpression.Uncast().Parenthesize() End If Throw ExceptionUtilities.UnexpectedValue(old) End Function Private Class MyCodeAction Inherits CustomCodeActions.DocumentChangeAction Public Sub New(createChangedDocument As Func(Of CancellationToken, Task(Of Document))) MyBase.New(AnalyzersResources.Remove_Unnecessary_Cast, createChangedDocument, NameOf(AnalyzersResources.Remove_Unnecessary_Cast)) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryCast <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveUnnecessaryCast), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.GenerateEndConstruct)> Partial Friend Class VisualBasicRemoveUnnecessaryCastCodeFixProvider Inherits SyntaxEditorBasedCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId) Friend NotOverridable Overrides ReadOnly Property CodeFixCategory As CodeFixCategory Get Return CodeFixCategory.CodeStyle End Get End Property Public Overrides Function RegisterCodeFixesAsync(context As CodeFixContext) As Task context.RegisterCodeFix(New MyCodeAction( Function(c) FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics) Return Task.CompletedTask End Function Private Shared Function IsUnnecessaryCast(node As ExpressionSyntax, model As SemanticModel, cancellationToken As CancellationToken) As Boolean Dim castExpression = TryCast(node, CastExpressionSyntax) If castExpression IsNot Nothing Then Return castExpression.IsUnnecessaryCast(model, assumeCallKeyword:=True, cancellationToken:=cancellationToken) End If Dim predefinedCastExpression = TryCast(node, PredefinedCastExpressionSyntax) If predefinedCastExpression IsNot Nothing Then Return predefinedCastExpression.IsUnnecessaryCast(model, assumeCallKeyword:=True, cancellationToken:=cancellationToken) End If Return False End Function Protected Overrides Async Function FixAllAsync( document As Document, diagnostics As ImmutableArray(Of Diagnostic), editor As SyntaxEditor, cancellationToken As CancellationToken) As Task ' VB parsing is extremely hairy. Unlike C#, it can be very dangerous to go and remove a ' cast. For example, if the cast is at the statement level, it may contain an ' expression that itself is not legal on its own at the top level (see below for an ' example of this). Similarly, removing the cast may make VB parse following code ' differently. ' ' In order to deal with all these concerns safely, we first complexify the surrounding ' statements containing the casts we want to remove. *Then* we remove the casts from ' inside that. ' ' As an example, consider: DirectCast(New Goo(), IGoo).Blah() This is ' legal code, but this is not: New Goo().Blah() ' ' (because 'new' cannot start a statement). ' So we need to instead generate: Call New Goo().Blah() Dim originalCastNodes = diagnostics.SelectAsArray( Function(d) DirectCast(d.AdditionalLocations(0).FindNode(getInnermostNodeForTie:=True, cancellationToken), ExpressionSyntax)) ' Keep track of the all the casts we want to fix up. We'll fix them up at the end ' after we've done all other manipulation. Dim trackedRoot = editor.OriginalRoot.TrackNodes(originalCastNodes) Dim trackedDocument = document.WithSyntaxRoot(trackedRoot) ' Now, go and expand all the containing statements of the nodes we want to edit. ' This is necessary to ensure that the code remains parseable and preserves semantics. Dim expandedRoot = Await ExpandSurroundingStatementsAsync(trackedDocument, originalCastNodes, cancellationToken).ConfigureAwait(False) Dim expandedDocument = document.WithSyntaxRoot(expandedRoot) Dim removedRoot = Await RemoveCastsAsync( expandedDocument, originalCastNodes, cancellationToken).ConfigureAwait(False) editor.ReplaceNode(editor.OriginalRoot, removedRoot) End Function Private Shared Async Function RemoveCastsAsync( document As Document, originalCastNodes As ImmutableArray(Of ExpressionSyntax), cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) ' Now, find the cast nodes again in the expanded document Dim currentCastNodes = root.GetCurrentNodes(originalCastNodes) Dim innerEditor = New SyntaxEditor(root, document.Project.Solution.Workspace) Await innerEditor.ApplyExpressionLevelSemanticEditsAsync( document, currentCastNodes.ToImmutableArray(), Function(semanticModel, castExpression) IsUnnecessaryCast(castExpression, semanticModel, cancellationToken), Function(unused, currentRoot, castExpression) Dim newCastExpression = Uncast(castExpression).WithAdditionalAnnotations(Formatter.Annotation) Return currentRoot.ReplaceNode(castExpression, newCastExpression) End Function, cancellationToken).ConfigureAwait(False) Return innerEditor.GetChangedRoot() End Function Private Shared Async Function ExpandSurroundingStatementsAsync( document As Document, originalNodes As ImmutableArray(Of ExpressionSyntax), cancellationToken As CancellationToken) As Task(Of SyntaxNode) Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) ' Note: we not only get the containing statement, but also the next statement after ' that. That's because the removal of the parens in the cast may then cause parsing ' problems with VB consuming the following line into the current line. This is most ' common with query clauses. By complexifying the next statement, we prevent that from ' happening. Dim trackedNodes = root.GetCurrentNodes(originalNodes) Dim containingAndNextStatements = trackedNodes.SelectMany( Function(n) Dim containingStatement = n.GetAncestorOrThis(Of StatementSyntax) Dim nextStatement = containingStatement.GetNextStatement() Return If(nextStatement Is Nothing, {containingStatement}, {containingStatement, nextStatement}) End Function).Distinct() Dim workspace = document.Project.Solution.Workspace Dim editor = New SyntaxEditor(root, workspace) For Each containingStatement In containingAndNextStatements Dim expandedStatement = Simplifier.Expand( containingStatement, semanticModel, workspace, cancellationToken:=cancellationToken) editor.ReplaceNode(containingStatement, expandedStatement) Next Return editor.GetChangedRoot() End Function Private Shared Function Uncast(old As ExpressionSyntax) As ExpressionSyntax ' parenthesize the uncasted value to help ensure any proper parsing. The excess ' parens will be removed if unnecessary. Dim castExpression = TryCast(old, CastExpressionSyntax) If castExpression IsNot Nothing Then Return castExpression.Uncast().Parenthesize() End If Dim predefinedCastExpression = TryCast(old, PredefinedCastExpressionSyntax) If predefinedCastExpression IsNot Nothing Then Return predefinedCastExpression.Uncast().Parenthesize() End If Throw ExceptionUtilities.UnexpectedValue(old) End Function Private Class MyCodeAction Inherits CustomCodeActions.DocumentChangeAction Public Sub New(createChangedDocument As Func(Of CancellationToken, Task(Of Document))) MyBase.New(AnalyzersResources.Remove_Unnecessary_Cast, createChangedDocument, NameOf(AnalyzersResources.Remove_Unnecessary_Cast)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Test/Symbol/Symbols/TypeResolutionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class TypeResolutionTests : CSharpTestBase { [Fact] public void TestGetTypeByNameAndArity() { string source1 = @" namespace System { public class TestClass { } public class TestClass<T> { } } "; string source2 = @" namespace System { public class TestClass { } } "; var c1 = CSharpCompilation.Create("Test1", syntaxTrees: new[] { Parse(source1) }, references: new[] { Net40.mscorlib }); Assert.Null(c1.GetTypeByMetadataName("DoesntExist")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2")); NamedTypeSymbol c1TestClass = c1.GetTypeByMetadataName("System.TestClass"); Assert.NotNull(c1TestClass); NamedTypeSymbol c1TestClassT = c1.GetTypeByMetadataName("System.TestClass`1"); Assert.NotNull(c1TestClassT); Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2")); var c2 = CSharpCompilation.Create("Test2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(source2) }, references: new MetadataReference[] { new CSharpCompilationReference(c1), Net40.mscorlib }); NamedTypeSymbol c2TestClass = c2.GetTypeByMetadataName("System.TestClass"); Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly); var c3 = CSharpCompilation.Create("Test3", references: new MetadataReference[] { new CSharpCompilationReference(c2), Net40.mscorlib }); NamedTypeSymbol c3TestClass = c3.GetTypeByMetadataName("System.TestClass"); Assert.NotSame(c2TestClass, c3TestClass); Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly)); Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1")); var c4 = CSharpCompilation.Create("Test4", references: new MetadataReference[] { new CSharpCompilationReference(c1), new CSharpCompilationReference(c2), Net40.mscorlib }); NamedTypeSymbol c4TestClass = c4.GetTypeByMetadataName("System.TestClass"); Assert.Null(c4TestClass); Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1")); } public class C<S, T> { public class D { public class E<U, V> { public class F<W> { } } } } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] public void TypeSymbolFromReflectionType() { var c = CSharpCompilation.Create("TypeSymbolFromReflectionType", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree("class C { }") }, references: new[] { MscorlibRef, MetadataReference.CreateFromImage(File.ReadAllBytes(typeof(TypeTests).GetTypeInfo().Assembly.Location)) }); var intSym = c.Assembly.GetTypeByReflectionType(typeof(int), includeReferences: true); Assert.NotNull(intSym); Assert.Equal(SpecialType.System_Int32, intSym.SpecialType); var strcmpSym = c.Assembly.GetTypeByReflectionType(typeof(StringComparison), includeReferences: true); Assert.NotNull(strcmpSym); Assert.Equal("System.StringComparison", strcmpSym.ToDisplayString()); var arraySym = c.Assembly.GetTypeByReflectionType(typeof(List<int>[][,,]), includeReferences: true); Assert.NotNull(arraySym); Assert.Equal("System.Collections.Generic.List<int>[][*,*,*]", arraySym.ToDisplayString()); var ptrSym = c.Assembly.GetTypeByReflectionType(typeof(char).MakePointerType().MakePointerType(), includeReferences: true); Assert.NotNull(ptrSym); Assert.Equal("char**", ptrSym.ToDisplayString()); string testType1 = typeof(C<,>).DeclaringType.FullName; var nestedSym1 = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, float>.F<byte>), includeReferences: true); Assert.Equal(testType1 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym1.ToDisplayString()); // Not supported atm: //string testType2 = typeof(C<,>).DeclaringType.FullName; //var nestedSym2 = c.Assembly.GetTypeByReflectionType(typeof(C<,>.D.E<,>.F<>), includeReferences: true); //Assert.Equal(testType2 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym2.ToDisplayString()); // Process is defined in System, which isn't referenced: var err = c.Assembly.GetTypeByReflectionType(typeof(C<Process, bool>.D.E<double, float>.F<byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, Process>.F<byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(Process[]), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(SyntaxKind).MakePointerType(), includeReferences: true); Assert.Null(err); } [Fact] public void AmbiguousNestedTypeSymbolFromMetadata() { var code = "class A { class B { } }"; var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); var c2 = CSharpCompilation.Create("Asm2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); var c3 = CSharpCompilation.Create("Asm3", references: new[] { new CSharpCompilationReference(c1), new CSharpCompilationReference(c2) }); Assert.Null(c3.GetTypeByMetadataName("A+B")); } [Fact] public void DuplicateNestedTypeSymbol() { var code = "class A { class B { } class B { } }"; var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToTestDisplayString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols { public class TypeResolutionTests : CSharpTestBase { [Fact] public void TestGetTypeByNameAndArity() { string source1 = @" namespace System { public class TestClass { } public class TestClass<T> { } } "; string source2 = @" namespace System { public class TestClass { } } "; var c1 = CSharpCompilation.Create("Test1", syntaxTrees: new[] { Parse(source1) }, references: new[] { Net40.mscorlib }); Assert.Null(c1.GetTypeByMetadataName("DoesntExist")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1")); Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2")); NamedTypeSymbol c1TestClass = c1.GetTypeByMetadataName("System.TestClass"); Assert.NotNull(c1TestClass); NamedTypeSymbol c1TestClassT = c1.GetTypeByMetadataName("System.TestClass`1"); Assert.NotNull(c1TestClassT); Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2")); var c2 = CSharpCompilation.Create("Test2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(source2) }, references: new MetadataReference[] { new CSharpCompilationReference(c1), Net40.mscorlib }); NamedTypeSymbol c2TestClass = c2.GetTypeByMetadataName("System.TestClass"); Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly); var c3 = CSharpCompilation.Create("Test3", references: new MetadataReference[] { new CSharpCompilationReference(c2), Net40.mscorlib }); NamedTypeSymbol c3TestClass = c3.GetTypeByMetadataName("System.TestClass"); Assert.NotSame(c2TestClass, c3TestClass); Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly)); Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1")); var c4 = CSharpCompilation.Create("Test4", references: new MetadataReference[] { new CSharpCompilationReference(c1), new CSharpCompilationReference(c2), Net40.mscorlib }); NamedTypeSymbol c4TestClass = c4.GetTypeByMetadataName("System.TestClass"); Assert.Null(c4TestClass); Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1")); } public class C<S, T> { public class D { public class E<U, V> { public class F<W> { } } } } [ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))] public void TypeSymbolFromReflectionType() { var c = CSharpCompilation.Create("TypeSymbolFromReflectionType", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree("class C { }") }, references: new[] { MscorlibRef, MetadataReference.CreateFromImage(File.ReadAllBytes(typeof(TypeTests).GetTypeInfo().Assembly.Location)) }); var intSym = c.Assembly.GetTypeByReflectionType(typeof(int), includeReferences: true); Assert.NotNull(intSym); Assert.Equal(SpecialType.System_Int32, intSym.SpecialType); var strcmpSym = c.Assembly.GetTypeByReflectionType(typeof(StringComparison), includeReferences: true); Assert.NotNull(strcmpSym); Assert.Equal("System.StringComparison", strcmpSym.ToDisplayString()); var arraySym = c.Assembly.GetTypeByReflectionType(typeof(List<int>[][,,]), includeReferences: true); Assert.NotNull(arraySym); Assert.Equal("System.Collections.Generic.List<int>[][*,*,*]", arraySym.ToDisplayString()); var ptrSym = c.Assembly.GetTypeByReflectionType(typeof(char).MakePointerType().MakePointerType(), includeReferences: true); Assert.NotNull(ptrSym); Assert.Equal("char**", ptrSym.ToDisplayString()); string testType1 = typeof(C<,>).DeclaringType.FullName; var nestedSym1 = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, float>.F<byte>), includeReferences: true); Assert.Equal(testType1 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym1.ToDisplayString()); // Not supported atm: //string testType2 = typeof(C<,>).DeclaringType.FullName; //var nestedSym2 = c.Assembly.GetTypeByReflectionType(typeof(C<,>.D.E<,>.F<>), includeReferences: true); //Assert.Equal(testType2 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym2.ToDisplayString()); // Process is defined in System, which isn't referenced: var err = c.Assembly.GetTypeByReflectionType(typeof(C<Process, bool>.D.E<double, float>.F<byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, Process>.F<byte>), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(Process[]), includeReferences: true); Assert.Null(err); err = c.Assembly.GetTypeByReflectionType(typeof(SyntaxKind).MakePointerType(), includeReferences: true); Assert.Null(err); } [Fact] public void AmbiguousNestedTypeSymbolFromMetadata() { var code = "class A { class B { } }"; var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); var c2 = CSharpCompilation.Create("Asm2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); var c3 = CSharpCompilation.Create("Asm3", references: new[] { new CSharpCompilationReference(c1), new CSharpCompilationReference(c2) }); Assert.Null(c3.GetTypeByMetadataName("A+B")); } [Fact] public void DuplicateNestedTypeSymbol() { var code = "class A { class B { } class B { } }"; var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) }); Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToTestDisplayString()); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/AnonymousTypeExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module AnonymousTypeExtensions <Extension()> Friend Function IsSubDescription(fields As ImmutableArray(Of AnonymousTypeField)) As Boolean Return fields.Last().Name Is AnonymousTypeDescriptor.SubReturnParameterName End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Module AnonymousTypeExtensions <Extension()> Friend Function IsSubDescription(fields As ImmutableArray(Of AnonymousTypeField)) As Boolean Return fields.Last().Name Is AnonymousTypeDescriptor.SubReturnParameterName End Function End Module End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationConversionSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConversionSymbol : CodeGenerationMethodSymbol { public CodeGenerationConversionSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol toType, IParameterSymbol fromType, bool isImplicit, ImmutableArray<AttributeData> toTypeAttributes, string documentationCommentXml) : base(containingType, attributes, declaredAccessibility, modifiers, returnType: toType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: isImplicit ? WellKnownMemberNames.ImplicitConversionName : WellKnownMemberNames.ExplicitConversionName, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray.Create(fromType), returnTypeAttributes: toTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.Conversion; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Editing; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConversionSymbol : CodeGenerationMethodSymbol { public CodeGenerationConversionSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, ITypeSymbol toType, IParameterSymbol fromType, bool isImplicit, ImmutableArray<AttributeData> toTypeAttributes, string documentationCommentXml) : base(containingType, attributes, declaredAccessibility, modifiers, returnType: toType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: isImplicit ? WellKnownMemberNames.ImplicitConversionName : WellKnownMemberNames.ExplicitConversionName, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray.Create(fromType), returnTypeAttributes: toTypeAttributes, documentationCommentXml) { } public override MethodKind MethodKind => MethodKind.Conversion; } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/Core/Portable/CodeFixes/CodeFixCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Represents a collection of <see cref="CodeFix"/>es supplied by a given fix provider /// (such as <see cref="CodeFixProvider"/> or <see cref="IConfigurationFixProvider"/>). /// </summary> internal class CodeFixCollection { public object Provider { get; } public TextSpan TextSpan { get; } public ImmutableArray<CodeFix> Fixes { get; } /// <summary> /// Optional fix all context, which is non-null if the given <see cref="Provider"/> supports fix all occurrences code fix. /// </summary> public FixAllState FixAllState { get; } public ImmutableArray<FixAllScope> SupportedScopes { get; } public Diagnostic FirstDiagnostic { get; } public CodeFixCollection( object provider, TextSpan span, ImmutableArray<CodeFix> fixes, FixAllState fixAllState, ImmutableArray<FixAllScope> supportedScopes, Diagnostic firstDiagnostic) { Provider = provider; TextSpan = span; Fixes = fixes.NullToEmpty(); FixAllState = fixAllState; SupportedScopes = supportedScopes.NullToEmpty(); FirstDiagnostic = firstDiagnostic; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Text; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Represents a collection of <see cref="CodeFix"/>es supplied by a given fix provider /// (such as <see cref="CodeFixProvider"/> or <see cref="IConfigurationFixProvider"/>). /// </summary> internal class CodeFixCollection { public object Provider { get; } public TextSpan TextSpan { get; } public ImmutableArray<CodeFix> Fixes { get; } /// <summary> /// Optional fix all context, which is non-null if the given <see cref="Provider"/> supports fix all occurrences code fix. /// </summary> public FixAllState FixAllState { get; } public ImmutableArray<FixAllScope> SupportedScopes { get; } public Diagnostic FirstDiagnostic { get; } public CodeFixCollection( object provider, TextSpan span, ImmutableArray<CodeFix> fixes, FixAllState fixAllState, ImmutableArray<FixAllScope> supportedScopes, Diagnostic firstDiagnostic) { Provider = provider; TextSpan = span; Fixes = fixes.NullToEmpty(); FixAllState = fixAllState; SupportedScopes = supportedScopes.NullToEmpty(); FirstDiagnostic = firstDiagnostic; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/Portable/SourceGeneration/Nodes/BatchNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class BatchNode<TInput> : IIncrementalGeneratorNode<ImmutableArray<TInput>> { private readonly IIncrementalGeneratorNode<TInput> _sourceNode; private readonly IEqualityComparer<ImmutableArray<TInput>> _comparer; public BatchNode(IIncrementalGeneratorNode<TInput> sourceNode, IEqualityComparer<ImmutableArray<TInput>>? comparer = null) { _sourceNode = sourceNode; _comparer = comparer ?? EqualityComparer<ImmutableArray<TInput>>.Default; } public IIncrementalGeneratorNode<ImmutableArray<TInput>> WithComparer(IEqualityComparer<ImmutableArray<TInput>> comparer) => new BatchNode<TInput>(_sourceNode, comparer); public NodeStateTable<ImmutableArray<TInput>> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<ImmutableArray<TInput>> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); // Semantics of a batch transform: // Batches will always exist (a batch of the empty table is still []) // There is only ever one input, the batch of the upstream table // - Output is cached when upstream is all cached // - Added when the previous table was empty // - Modified otherwise var source = sourceTable.Batch(); // update the table var newTable = previousTable.ToBuilder(); if (!sourceTable.IsCached || !newTable.TryUseCachedEntries()) { if (!newTable.TryModifyEntry(source, _comparer)) { newTable.AddEntry(source, EntryState.Added); } } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class BatchNode<TInput> : IIncrementalGeneratorNode<ImmutableArray<TInput>> { private readonly IIncrementalGeneratorNode<TInput> _sourceNode; private readonly IEqualityComparer<ImmutableArray<TInput>> _comparer; public BatchNode(IIncrementalGeneratorNode<TInput> sourceNode, IEqualityComparer<ImmutableArray<TInput>>? comparer = null) { _sourceNode = sourceNode; _comparer = comparer ?? EqualityComparer<ImmutableArray<TInput>>.Default; } public IIncrementalGeneratorNode<ImmutableArray<TInput>> WithComparer(IEqualityComparer<ImmutableArray<TInput>> comparer) => new BatchNode<TInput>(_sourceNode, comparer); public NodeStateTable<ImmutableArray<TInput>> UpdateStateTable(DriverStateTable.Builder builder, NodeStateTable<ImmutableArray<TInput>> previousTable, CancellationToken cancellationToken) { // grab the source inputs var sourceTable = builder.GetLatestStateTableForNode(_sourceNode); // Semantics of a batch transform: // Batches will always exist (a batch of the empty table is still []) // There is only ever one input, the batch of the upstream table // - Output is cached when upstream is all cached // - Added when the previous table was empty // - Modified otherwise var source = sourceTable.Batch(); // update the table var newTable = previousTable.ToBuilder(); if (!sourceTable.IsCached || !newTable.TryUseCachedEntries()) { if (!newTable.TryModifyEntry(source, _comparer)) { newTable.AddEntry(source, EntryState.Added); } } return newTable.ToImmutableAndFree(); } public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _sourceNode.RegisterOutput(output); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IRaiseEventStatement.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEvent() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEventWithArguments() Dim source = <![CDATA[ Imports System Class TestClass Public Event MyEvent(x As String, y As Integer) Sub M() RaiseEvent MyEvent(y:=1, x:=String.Empty)'BIND:"RaiseEvent MyEvent(y:=1, x:=String.Empty)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... ring.Empty)') Event Reference: IEventReferenceOperation: Event TestClass.MyEvent(x As System.String, y As System.Int32) (OperationKind.EventReference, Type: TestClass.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x:=String.Empty') IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'String.Empty') Instance Receiver: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y:=1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseSharedEvent() Dim source = <![CDATA[ Imports System Class TestClass Shared Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEventWithExtraArgument() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent(1)'BIND:"RaiseEvent TestEvent(1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'RaiseEvent TestEvent(1)') Children(1): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'RaiseEvent TestEvent(1)') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'RaiseEvent TestEvent(1)') Children(1): IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action, IsImplicit) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Public Event TestEvent As Action'. RaiseEvent TestEvent(1)'BIND:"RaiseEvent TestEvent(1)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseUndefinedEvent() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent2()'BIND:"RaiseEvent TestEvent2()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'RaiseEvent TestEvent2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'TestEvent2') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'TestEvent2' is not declared. It may be inaccessible due to its protection level. RaiseEvent TestEvent2()'BIND:"RaiseEvent TestEvent2()" ~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseEventThroughField1() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() TestEventEvent()'BIND:"TestEventEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation (virtual Sub System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'TestEventEvent()') Instance Receiver: IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action) (Syntax: 'TestEventEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEventEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseEventThroughField2() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() TestEventEvent.Invoke()'BIND:"TestEventEvent.Invoke()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation (virtual Sub System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'TestEventEvent.Invoke()') Instance Receiver: IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action) (Syntax: 'TestEventEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEventEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseCustomEvent() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseCustomEventWithArguments() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Eventhandler AddHandler(value As Eventhandler) End AddHandler RemoveHandler(value As Eventhandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Sub M() RaiseEvent TestEvent(Nothing, Nothing)'BIND:"RaiseEvent TestEvent(Nothing, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... g, Nothing)') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: sender) (OperationKind.Argument, Type: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') InConversion: CommonConversion (Exists: True, 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: e) (OperationKind.Argument, Type: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.EventArgs, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub EventAccessFromRaiseEventShouldReturnEventReference() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"TestEvent" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub EventAccessFromRaiseCustomEventShouldReturnEventReference() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Sub M() RaiseEvent TestEvent()'BIND:"TestEvent" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_NoControlFlow() Dim source = <![CDATA[ Imports System Class C1 Public Shared Event MyEvent1() Public Event MyEvent2(x As String) Sub M(x As String)'BIND:"Sub M(x As String)" RaiseEvent MyEvent1() RaiseEvent MyEvent2(x) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent1()') Event Reference: IEventReferenceOperation: Event C1.MyEvent1() (Static) (OperationKind.EventReference, Type: C1.MyEvent1EventHandler) (Syntax: 'MyEvent1') Instance Receiver: null Arguments(0) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent2(x)') Event Reference: IEventReferenceOperation: Event C1.MyEvent2(x As System.String) (OperationKind.EventReference, Type: C1.MyEvent2EventHandler) (Syntax: 'MyEvent2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowNullReceiver() Dim source = <![CDATA[ Imports System Class C1 Public Shared Event MyEvent(x As String) Sub M(x As String) 'BIND:"Sub M(x As String)" RaiseEvent MyEvent(x) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent(x)') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String) (Static) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub ' Note: Control flow is not possible in the EventReference for the RaiseEvent statement as ' the first token after RaiseEvent is parsed as an identifier. ' Hence, we only test control flow in the RaiseEvent arguments. <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInFirstArgument() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y As String) 'BIND:"Sub M(x1 As String, x2 As String, y As String)" RaiseEvent MyEvent(If(x1, x2), y) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') 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: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... x1, x2), y)') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInSecondArgument() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y As String) 'BIND:"Sub M(x1 As String, x2 As String, y As String)" RaiseEvent MyEvent(y, If(x1, x2)) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... If(x1, x2))') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'y') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInMultipleArguments() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y1 As String, y2 As String) 'BIND:"Sub M(x1 As String, x2 As String, y1 As String, y2 As String)" RaiseEvent MyEvent(If(x1, x2), If(y1, y2)) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') 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: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... If(y1, y2))') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'If(y1, y2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(y1, y2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEvent() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEventWithArguments() Dim source = <![CDATA[ Imports System Class TestClass Public Event MyEvent(x As String, y As Integer) Sub M() RaiseEvent MyEvent(y:=1, x:=String.Empty)'BIND:"RaiseEvent MyEvent(y:=1, x:=String.Empty)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... ring.Empty)') Event Reference: IEventReferenceOperation: Event TestClass.MyEvent(x As System.String, y As System.Int32) (OperationKind.EventReference, Type: TestClass.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x:=String.Empty') IFieldReferenceOperation: System.String.Empty As System.String (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'String.Empty') Instance Receiver: null InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y:=1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseSharedEvent() Dim source = <![CDATA[ Imports System Class TestClass Shared Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (Static) (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: null Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseInstanceEventWithExtraArgument() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent(1)'BIND:"RaiseEvent TestEvent(1)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'RaiseEvent TestEvent(1)') Children(1): IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid, IsImplicit) (Syntax: 'RaiseEvent TestEvent(1)') Children(2): IOperation: (OperationKind.None, Type: null, IsInvalid, IsImplicit) (Syntax: 'RaiseEvent TestEvent(1)') Children(1): IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action, IsImplicit) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30057: Too many arguments to 'Public Event TestEvent As Action'. RaiseEvent TestEvent(1)'BIND:"RaiseEvent TestEvent(1)" ~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseUndefinedEvent() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent2()'BIND:"RaiseEvent TestEvent2()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: 'RaiseEvent TestEvent2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'TestEvent2') Children(0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30451: 'TestEvent2' is not declared. It may be inaccessible due to its protection level. RaiseEvent TestEvent2()'BIND:"RaiseEvent TestEvent2()" ~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseEventThroughField1() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() TestEventEvent()'BIND:"TestEventEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation (virtual Sub System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'TestEventEvent()') Instance Receiver: IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action) (Syntax: 'TestEventEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEventEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseEventThroughField2() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() TestEventEvent.Invoke()'BIND:"TestEventEvent.Invoke()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IInvocationOperation (virtual Sub System.Action.Invoke()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'TestEventEvent.Invoke()') Instance Receiver: IFieldReferenceOperation: TestClass.TestEventEvent As System.Action (OperationKind.FieldReference, Type: System.Action) (Syntax: 'TestEventEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEventEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of InvocationExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseCustomEvent() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Sub M() RaiseEvent TestEvent()'BIND:"RaiseEvent TestEvent()" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent TestEvent()') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub RaiseCustomEventWithArguments() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Eventhandler AddHandler(value As Eventhandler) End AddHandler RemoveHandler(value As Eventhandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event Sub M() RaiseEvent TestEvent(Nothing, Nothing)'BIND:"RaiseEvent TestEvent(Nothing, Nothing)" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... g, Nothing)') Event Reference: IEventReferenceOperation: Event TestClass.TestEvent As System.EventHandler (OperationKind.EventReference, Type: System.EventHandler) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: sender) (OperationKind.Argument, Type: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') InConversion: CommonConversion (Exists: True, 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: e) (OperationKind.Argument, Type: null) (Syntax: 'Nothing') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.EventArgs, Constant: null, IsImplicit) (Syntax: 'Nothing') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of RaiseEventStatementSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub EventAccessFromRaiseEventShouldReturnEventReference() Dim source = <![CDATA[ Imports System Class TestClass Event TestEvent As Action Sub M() RaiseEvent TestEvent()'BIND:"TestEvent" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact> Public Sub EventAccessFromRaiseCustomEventShouldReturnEventReference() Dim source = <![CDATA[ Imports System Class TestClass Public Custom Event TestEvent As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event Sub M() RaiseEvent TestEvent()'BIND:"TestEvent" End Sub End Class]]>.Value Dim expectedOperationTree = <![CDATA[ IEventReferenceOperation: Event TestClass.TestEvent As System.Action (OperationKind.EventReference, Type: System.Action) (Syntax: 'TestEvent') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: TestClass, IsImplicit) (Syntax: 'TestEvent') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_NoControlFlow() Dim source = <![CDATA[ Imports System Class C1 Public Shared Event MyEvent1() Public Event MyEvent2(x As String) Sub M(x As String)'BIND:"Sub M(x As String)" RaiseEvent MyEvent1() RaiseEvent MyEvent2(x) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent1()') Event Reference: IEventReferenceOperation: Event C1.MyEvent1() (Static) (OperationKind.EventReference, Type: C1.MyEvent1EventHandler) (Syntax: 'MyEvent1') Instance Receiver: null Arguments(0) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent2(x)') Event Reference: IEventReferenceOperation: Event C1.MyEvent2(x As System.String) (OperationKind.EventReference, Type: C1.MyEvent2EventHandler) (Syntax: 'MyEvent2') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent2') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowNullReceiver() Dim source = <![CDATA[ Imports System Class C1 Public Shared Event MyEvent(x As String) Sub M(x As String) 'BIND:"Sub M(x As String)" RaiseEvent MyEvent(x) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent MyEvent(x)') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String) (Static) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'x') IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub ' Note: Control flow is not possible in the EventReference for the RaiseEvent statement as ' the first token after RaiseEvent is parsed as an identifier. ' Hence, we only test control flow in the RaiseEvent arguments. <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInFirstArgument() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y As String) 'BIND:"Sub M(x1 As String, x2 As String, y As String)" RaiseEvent MyEvent(If(x1, x2), y) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') 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: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... x1, x2), y)') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'y') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInSecondArgument() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y As String) 'BIND:"Sub M(x1 As String, x2 As String, y As String)" RaiseEvent MyEvent(y, If(x1, x2)) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... If(x1, x2))') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'y') IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact()> Public Sub RaiseEvent_ControlFlowInMultipleArguments() Dim source = <![CDATA[ Imports System Class C1 Public Event MyEvent(x As String, y As String) Sub M(x1 As String, x2 As String, y1 As String, y2 As String) 'BIND:"Sub M(x1 As String, x2 As String, y1 As String, y2 As String)" RaiseEvent MyEvent(If(x1, x2), If(y1, y2)) End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'MyEvent') Value: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') 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: 'x1') Value: IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'x1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'x1') Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x2') Value: IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'x2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IParameterReferenceOperation: y1 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'y1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'y1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y2') Value: IParameterReferenceOperation: y2 (OperationKind.ParameterReference, Type: System.String) (Syntax: 'y2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IRaiseEventOperation (OperationKind.RaiseEvent, Type: null) (Syntax: 'RaiseEvent ... If(y1, y2))') Event Reference: IEventReferenceOperation: Event C1.MyEvent(x As System.String, y As System.String) (OperationKind.EventReference, Type: C1.MyEventEventHandler) (Syntax: 'MyEvent') Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C1, IsImplicit) (Syntax: 'MyEvent') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: 'If(x1, x2)') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(x1, x2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: y) (OperationKind.Argument, Type: null) (Syntax: 'If(y1, y2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.String, IsImplicit) (Syntax: 'If(y1, y2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/CodeAnalysisTest/Text/StringText_LineTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringText_LineTest { [Fact] public void FromSpanNotIncludingBreaks() { string newLine = Environment.NewLine; var text = SourceText.From("goo" + newLine); var span = new TextSpan(0, 3); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.Span); Assert.Equal(3 + newLine.Length, line.EndIncludingLineBreak); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaksAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(3, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaks() { var text = SourceText.From("goo" + Environment.NewLine + "bar"); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(text.Length, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanNoBreaksBeforeOrAfter() { var text = SourceText.From("goo"); var line = TextLine.FromSpan(text, new TextSpan(0, 3)); Assert.Equal("goo", line.ToString()); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanZeroLengthNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 0))); } [Fact] public void FromSpanNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 3))); } [Fact] public void FromSpanNotStartOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 5))); } [Fact] public void FromSpanZeroLengthAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var start = text.Length; var line = TextLine.FromSpan(text, new TextSpan(start, 0)); Assert.Equal("", line.ToString()); Assert.Equal(0, line.Span.Length); Assert.Equal(0, line.SpanIncludingLineBreak.Length); Assert.Equal(start, line.Start); Assert.Equal(start, line.Span.Start); Assert.Equal(start, line.SpanIncludingLineBreak.Start); Assert.Equal(1, line.LineNumber); } [Fact] public void FromSpanZeroLengthWithLineBreak() { var text = SourceText.From(Environment.NewLine); var line = TextLine.FromSpan(text, new TextSpan(0, 0)); Assert.Equal("", line.ToString()); Assert.Equal(Environment.NewLine.Length, line.SpanIncludingLineBreak.Length); } [Fact] public void FromSpanLengthGreaterThanTextThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 10))); } [Fact] public void FromSpanStartsBeforeZeroThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(-1, 2))); } [Fact] public void FromSpanZeroLengthBeyondEndThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(7, 0))); } [Fact] public void FromSpanTextNullThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentNullException>(() => TextLine.FromSpan(null, new TextSpan(0, 2))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringText_LineTest { [Fact] public void FromSpanNotIncludingBreaks() { string newLine = Environment.NewLine; var text = SourceText.From("goo" + newLine); var span = new TextSpan(0, 3); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.Span); Assert.Equal(3 + newLine.Length, line.EndIncludingLineBreak); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaksAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(3, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanIncludingBreaks() { var text = SourceText.From("goo" + Environment.NewLine + "bar"); var span = TextSpan.FromBounds(0, text.Length); var line = TextLine.FromSpan(text, span); Assert.Equal(span, line.SpanIncludingLineBreak); Assert.Equal(text.Length, line.End); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanNoBreaksBeforeOrAfter() { var text = SourceText.From("goo"); var line = TextLine.FromSpan(text, new TextSpan(0, 3)); Assert.Equal("goo", line.ToString()); Assert.Equal(0, line.LineNumber); } [Fact] public void FromSpanZeroLengthNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 0))); } [Fact] public void FromSpanNotEndOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(0, 3))); } [Fact] public void FromSpanNotStartOfLineThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 5))); } [Fact] public void FromSpanZeroLengthAtEnd() { var text = SourceText.From("goo" + Environment.NewLine); var start = text.Length; var line = TextLine.FromSpan(text, new TextSpan(start, 0)); Assert.Equal("", line.ToString()); Assert.Equal(0, line.Span.Length); Assert.Equal(0, line.SpanIncludingLineBreak.Length); Assert.Equal(start, line.Start); Assert.Equal(start, line.Span.Start); Assert.Equal(start, line.SpanIncludingLineBreak.Start); Assert.Equal(1, line.LineNumber); } [Fact] public void FromSpanZeroLengthWithLineBreak() { var text = SourceText.From(Environment.NewLine); var line = TextLine.FromSpan(text, new TextSpan(0, 0)); Assert.Equal("", line.ToString()); Assert.Equal(Environment.NewLine.Length, line.SpanIncludingLineBreak.Length); } [Fact] public void FromSpanLengthGreaterThanTextThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(1, 10))); } [Fact] public void FromSpanStartsBeforeZeroThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(-1, 2))); } [Fact] public void FromSpanZeroLengthBeyondEndThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentOutOfRangeException>(() => TextLine.FromSpan(text, new TextSpan(7, 0))); } [Fact] public void FromSpanTextNullThrows() { var text = SourceText.From("abcdef"); Assert.Throws<ArgumentNullException>(() => TextLine.FromSpan(null, new TextSpan(0, 2))); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/VSTypeScriptProjectDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [DiagnosticAnalyzer(InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptProjectDiagnosticAnalyzer : ProjectDiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty; public override Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { var analyzer = project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation; if (analyzer == null) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return analyzer.AnalyzeProjectAsync(project, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript { [DiagnosticAnalyzer(InternalLanguageNames.TypeScript)] internal sealed class VSTypeScriptProjectDiagnosticAnalyzer : ProjectDiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray<DiagnosticDescriptor>.Empty; public override Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { var analyzer = project.LanguageServices.GetRequiredService<VSTypeScriptDiagnosticAnalyzerLanguageService>().Implementation; if (analyzer == null) { return SpecializedTasks.EmptyImmutableArray<Diagnostic>(); } return analyzer.AnalyzeProjectAsync(project, cancellationToken); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Core/Implementation/InlineRename/HighlightTags/RenameConflictTag.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags { internal class RenameConflictTag : TextMarkerTag { // Only used for theming, does not need localized internal const string TagId = "RoslynRenameConflictTag"; public static readonly RenameConflictTag Instance = new RenameConflictTag(); private RenameConflictTag() : base(TagId) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags { internal class RenameConflictTag : TextMarkerTag { // Only used for theming, does not need localized internal const string TagId = "RoslynRenameConflictTag"; public static readonly RenameConflictTag Instance = new RenameConflictTag(); private RenameConflictTag() : base(TagId) { } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/Core/Portable/Diagnostics/AnalyzerHelper.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { // These are the error codes of the compiler warnings. // Keep the ids the same so that de-duplication against compiler errors // works in the error list (after a build). internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032"; internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376"; internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033"; internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377"; internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034"; internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378"; internal const string WRN_AnalyzerReferencesNetFrameworkIdCS = "CS8850"; internal const string WRN_AnalyzerReferencesNetFrameworkIdVB = "BC42503"; // Shared with Compiler internal const string AnalyzerExceptionDiagnosticId = "AD0001"; internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002"; // IDE only errors internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000"; internal const string WRN_NoAnalyzerInAssemblyId = "AD1001"; internal const string WRN_UnableToLoadAnalyzerId = "AD1002"; internal const string WRN_AnalyzerReferencesNetFrameworkId = "AD1003"; private const string AnalyzerExceptionDiagnosticCategory = "Intellisense"; public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer) => analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer || analyzer == FileContentLoadAnalyzer.Instance; public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer) => analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer(); public static bool IsOpenFileOnly(this DiagnosticAnalyzer analyzer, OptionSet options) => analyzer is IBuiltInAnalyzer builtInAnalyzer && builtInAnalyzer.OpenFileOnly(options); public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? descriptor.DefaultSeverity.ToReportDiagnostic() : descriptor.GetEffectiveSeverity(options); } public static (string analyzerId, VersionStamp version) GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer) { // Get the unique ID for given diagnostic analyzer. // note that we also put version stamp so that we can detect changed analyzer. var typeInfo = analyzer.GetType().GetTypeInfo(); return (analyzer.GetAnalyzerId(), GetAnalyzerVersion(typeInfo.Assembly.Location)); } public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer) => analyzer.GetType().Assembly.GetName().Name ?? throw ExceptionUtilities.Unreachable; public static OptionSet GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionSetAsync = GetAnalyzerOptionSetAsync(analyzerOptions, syntaxTree, cancellationToken); if (optionSetAsync.IsCompleted) return optionSetAsync.Result; return optionSetAsync.AsTask().GetAwaiter().GetResult(); } public static async ValueTask<OptionSet> GetAnalyzerOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var configOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); #pragma warning disable CS0612 // Type or member is obsolete var optionSet = await GetDocumentOptionSetAsync(analyzerOptions, syntaxTree, cancellationToken).ConfigureAwait(false); #pragma warning restore CS0612 // Type or member is obsolete return new AnalyzerConfigOptionSet(configOptions, optionSet); } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, ILanguageSpecificOption<T> option, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync<T>(analyzerOptions, option, language: null, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) return optionAsync.Result; return optionAsync.AsTask().GetAwaiter().GetResult(); } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, IPerLanguageOption<T> option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync<T>(analyzerOptions, option, language, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) return optionAsync.Result; return optionAsync.AsTask().GetAwaiter().GetResult(); } public static async ValueTask<T> GetOptionAsync<T>(this AnalyzerOptions analyzerOptions, IOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (analyzerOptions.TryGetEditorConfigOption<T>(option, syntaxTree, out var value)) { return value; } #pragma warning disable CS0612 // Type or member is obsolete var optionSet = await analyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).ConfigureAwait(false); #pragma warning restore CS0612 // Type or member is obsolete if (optionSet != null) { value = optionSet.GetOption<T>(new OptionKey(option, language)); } return value ?? (T)option.DefaultValue!; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public static ValueTask<OptionSet?> GetDocumentOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (analyzerOptions is not WorkspaceAnalyzerOptions workspaceAnalyzerOptions) { return ValueTaskFactory.FromResult((OptionSet?)null); } return workspaceAnalyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken); } /// <summary> /// Create a diagnostic for exception thrown by the given analyzer. /// </summary> /// <remarks> /// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic". /// </remarks> internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e) { var analyzerName = analyzer.ToString(); // TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance. // However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field. // This requires us to create a new DiagnosticDescriptor instance per diagnostic instance. var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId, title: FeaturesResources.User_Diagnostic_Analyzer_Failure, messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2, description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()), category: AnalyzerExceptionDiagnosticCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message); } private static VersionStamp GetAnalyzerVersion(string path) { if (path == null || !File.Exists(path)) { return VersionStamp.Default; } return VersionStamp.Create(File.GetLastWriteTimeUtc(path)); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(AnalyzerLoadFailureEventArgs e, string fullPath, ProjectId? projectId, string? language) { static string GetLanguageSpecificId(string? language, string noLanguageId, string csharpId, string vbId) => language == null ? noLanguageId : (language == LanguageNames.CSharp) ? csharpId : vbId; string id, messageFormat, message; switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: id = GetLanguageSpecificId(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB); messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1; message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: id = GetLanguageSpecificId(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB); messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2; message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: id = GetLanguageSpecificId(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB); messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers; message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: id = GetLanguageSpecificId(language, WRN_AnalyzerReferencesNetFrameworkId, WRN_AnalyzerReferencesNetFrameworkIdCS, WRN_AnalyzerReferencesNetFrameworkIdVB); messageFormat = FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework; message = string.Format(FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework, fullPath, e.TypeName); break; default: throw ExceptionUtilities.UnexpectedValue(e.ErrorCode); } var description = e.Exception.CreateDiagnosticDescription(); return new DiagnosticData( id, FeaturesResources.Roslyn_HostError, message, messageFormat, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description, warningLevel: 0, projectId: projectId, customTags: ImmutableArray<string>.Empty, properties: ImmutableDictionary<string, string?>.Empty, language: language); } public static void AppendAnalyzerMap(this Dictionary<string, DiagnosticAnalyzer> analyzerMap, IEnumerable<DiagnosticAnalyzer> analyzers) { foreach (var analyzer in analyzers) { // user might have included exact same analyzer twice as project analyzers explicitly. we consider them as one analyzerMap[analyzer.GetAnalyzerId()] = analyzer; } } public static IEnumerable<AnalyzerPerformanceInfo> ToAnalyzerPerformanceInfo(this IDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> analysisResult, DiagnosticAnalyzerInfoCache analyzerInfo) => analysisResult.Select(kv => new AnalyzerPerformanceInfo(kv.Key.GetAnalyzerId(), analyzerInfo.IsTelemetryCollectionAllowed(kv.Key), kv.Value.ExecutionTime)); public static async Task<CompilationWithAnalyzers?> CreateCompilationWithAnalyzersAsync( Project project, IEnumerable<DiagnosticAnalyzer> analyzers, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); if (compilation == null) { // project doesn't support compilation return null; } // Create driver that holds onto compilation and associated analyzers var filteredAnalyzers = analyzers.Where(a => !a.IsWorkspaceDiagnosticAnalyzer()).ToImmutableArrayOrEmpty(); // PERF: there is no analyzers for this compilation. // compilationWithAnalyzer will throw if it is created with no analyzers which is perf optimization. if (filteredAnalyzers.IsEmpty) { return null; } Contract.ThrowIfFalse(project.SupportsCompilation); AssertCompilation(project, compilation); // in IDE, we always set concurrentAnalysis == false otherwise, we can get into thread starvation due to // async being used with synchronous blocking concurrency. var analyzerOptions = new CompilationWithAnalyzersOptions( options: new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution), onAnalyzerException: null, analyzerExceptionFilter: GetAnalyzerExceptionFilter(), concurrentAnalysis: false, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: includeSuppressedDiagnostics); // Create driver that holds onto compilation and associated analyzers return compilation.WithAnalyzers(filteredAnalyzers, analyzerOptions); Func<Exception, bool> GetAnalyzerExceptionFilter() { return ex => { if (ex is not OperationCanceledException && project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException)) { // report telemetry FatalError.ReportAndPropagate(ex); // force fail fast (the host might not crash when reporting telemetry): FailFast.OnFatalException(ex); } return true; }; } } [Conditional("DEBUG")] private static void AssertCompilation(Project project, Compilation compilation1) { // given compilation must be from given project. Contract.ThrowIfFalse(project.TryGetCompilation(out var compilation2)); Contract.ThrowIfFalse(compilation1 == compilation2); } public static async Task<ImmutableArray<Diagnostic>> ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync( DocumentDiagnosticAnalyzer analyzer, Document document, AnalysisKind kind, Compilation? compilation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ImmutableArray<Diagnostic> diagnostics; try { var analyzeAsync = kind switch { AnalysisKind.Syntax => analyzer.AnalyzeSyntaxAsync(document, cancellationToken), AnalysisKind.Semantic => analyzer.AnalyzeSemanticsAsync(document, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; diagnostics = (await analyzeAsync.ConfigureAwait(false)).NullToEmpty(); #if DEBUG // since all DocumentDiagnosticAnalyzers are from internal users, we only do debug check. also this can be expensive at runtime // since it requires await. if we find any offender through NFW, we should be able to fix those since all those should // from intern teams. await VerifyDiagnosticLocationsAsync(diagnostics, document.Project, cancellationToken).ConfigureAwait(false); #endif } catch (Exception e) when (!IsCanceled(e, cancellationToken)) { diagnostics = ImmutableArray.Create(CreateAnalyzerExceptionDiagnostic(analyzer, e)); } if (compilation != null) { diagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).ToImmutableArrayOrEmpty(); } return diagnostics; } public static async Task<ImmutableArray<Diagnostic>> ComputeProjectDiagnosticAnalyzerDiagnosticsAsync( ProjectDiagnosticAnalyzer analyzer, Project project, Compilation? compilation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ImmutableArray<Diagnostic> diagnostics; try { diagnostics = (await analyzer.AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false)).NullToEmpty(); #if DEBUG // since all ProjectDiagnosticAnalyzers are from internal users, we only do debug check. also this can be expensive at runtime // since it requires await. if we find any offender through NFW, we should be able to fix those since all those should // from intern teams. await VerifyDiagnosticLocationsAsync(diagnostics, project, cancellationToken).ConfigureAwait(false); #endif } catch (Exception e) when (!IsCanceled(e, cancellationToken)) { diagnostics = ImmutableArray.Create(CreateAnalyzerExceptionDiagnostic(analyzer, e)); } // Apply filtering from compilation options (source suppressions, ruleset, etc.) if (compilation != null) { diagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).ToImmutableArrayOrEmpty(); } return diagnostics; } private static bool IsCanceled(Exception ex, CancellationToken cancellationToken) => (ex as OperationCanceledException)?.CancellationToken == cancellationToken; #if DEBUG private static async Task VerifyDiagnosticLocationsAsync(ImmutableArray<Diagnostic> diagnostics, Project project, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { await VerifyDiagnosticLocationAsync(diagnostic.Id, diagnostic.Location).ConfigureAwait(false); if (diagnostic.AdditionalLocations != null) { foreach (var location in diagnostic.AdditionalLocations) { await VerifyDiagnosticLocationAsync(diagnostic.Id, location).ConfigureAwait(false); } } } async Task VerifyDiagnosticLocationAsync(string id, Location location) { switch (location.Kind) { case LocationKind.None: case LocationKind.MetadataFile: case LocationKind.XmlFile: // ignore these kinds break; case LocationKind.SourceFile: { RoslynDebug.Assert(location.SourceTree != null); if (project.GetDocument(location.SourceTree) == null) { // Disallow diagnostics with source locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_in_file_1_which_is_not_part_of_the_compilation_being_analyzed, id, location.SourceTree.FilePath), "diagnostic"); } if (location.SourceSpan.End > location.SourceTree.Length) { // Disallow diagnostics with source locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file, id, location.SourceSpan, location.SourceTree.FilePath), "diagnostic"); } } break; case LocationKind.ExternalFile: { var filePath = location.GetLineSpan().Path; var document = TryGetDocumentWithFilePath(filePath); if (document == null) { // this is not a roslyn file. we don't care about this file. return; } // this can be potentially expensive since it will load text if it is not already loaded. // but, this text is most likely already loaded since producer of this diagnostic (Document/ProjectDiagnosticAnalyzers) // should have loaded it to produce the diagnostic at the first place. once loaded, it should stay in memory until // project cache goes away. when text is already there, await should return right away. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (location.SourceSpan.End > text.Length) { // Disallow diagnostics with locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file, id, location.SourceSpan, filePath), "diagnostic"); } } break; default: throw ExceptionUtilities.Unreachable; } } Document? TryGetDocumentWithFilePath(string path) { foreach (var documentId in project.Solution.GetDocumentIdsWithFilePath(path)) { if (documentId.ProjectId == project.Id) { return project.GetDocument(documentId); } } return null; } } #endif public static IEnumerable<DiagnosticData> ConvertToLocalDiagnostics(this IEnumerable<Diagnostic> diagnostics, TextDocument targetTextDocument, TextSpan? span = null) { foreach (var diagnostic in diagnostics) { if (!IsReportedInDocument(diagnostic, targetTextDocument)) { continue; } if (span.HasValue && !span.Value.IntersectsWith(diagnostic.Location.SourceSpan)) { continue; } yield return DiagnosticData.Create(diagnostic, targetTextDocument); } static bool IsReportedInDocument(Diagnostic diagnostic, TextDocument targetTextDocument) { if (diagnostic.Location.SourceTree != null) { return targetTextDocument.Project.GetDocument(diagnostic.Location.SourceTree) == targetTextDocument; } else if (diagnostic.Location.Kind == LocationKind.ExternalFile) { var lineSpan = diagnostic.Location.GetLineSpan(); var documentIds = targetTextDocument.Project.Solution.GetDocumentIdsWithFilePath(lineSpan.Path); return documentIds.Any(id => id == targetTextDocument.Id); } return false; } } #if DEBUG internal static bool AreEquivalent(Diagnostic[] diagnosticsA, Diagnostic[] diagnosticsB) { var set = new HashSet<Diagnostic>(diagnosticsA, DiagnosticComparer.Instance); return set.SetEquals(diagnosticsB); } private sealed class DiagnosticComparer : IEqualityComparer<Diagnostic?> { internal static readonly DiagnosticComparer Instance = new(); public bool Equals(Diagnostic? x, Diagnostic? y) { if (x is null) return y is null; else if (y is null) return false; return x.Id == y.Id && x.Location == y.Location; } public int GetHashCode(Diagnostic? obj) { if (obj is null) return 0; return Hash.Combine(obj.Id.GetHashCode(), obj.Location.GetHashCode()); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Telemetry; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal static partial class AnalyzerHelper { // These are the error codes of the compiler warnings. // Keep the ids the same so that de-duplication against compiler errors // works in the error list (after a build). internal const string WRN_AnalyzerCannotBeCreatedIdCS = "CS8032"; internal const string WRN_AnalyzerCannotBeCreatedIdVB = "BC42376"; internal const string WRN_NoAnalyzerInAssemblyIdCS = "CS8033"; internal const string WRN_NoAnalyzerInAssemblyIdVB = "BC42377"; internal const string WRN_UnableToLoadAnalyzerIdCS = "CS8034"; internal const string WRN_UnableToLoadAnalyzerIdVB = "BC42378"; internal const string WRN_AnalyzerReferencesNetFrameworkIdCS = "CS8850"; internal const string WRN_AnalyzerReferencesNetFrameworkIdVB = "BC42503"; // Shared with Compiler internal const string AnalyzerExceptionDiagnosticId = "AD0001"; internal const string AnalyzerDriverExceptionDiagnosticId = "AD0002"; // IDE only errors internal const string WRN_AnalyzerCannotBeCreatedId = "AD1000"; internal const string WRN_NoAnalyzerInAssemblyId = "AD1001"; internal const string WRN_UnableToLoadAnalyzerId = "AD1002"; internal const string WRN_AnalyzerReferencesNetFrameworkId = "AD1003"; private const string AnalyzerExceptionDiagnosticCategory = "Intellisense"; public static bool IsWorkspaceDiagnosticAnalyzer(this DiagnosticAnalyzer analyzer) => analyzer is DocumentDiagnosticAnalyzer || analyzer is ProjectDiagnosticAnalyzer || analyzer == FileContentLoadAnalyzer.Instance; public static bool IsBuiltInAnalyzer(this DiagnosticAnalyzer analyzer) => analyzer is IBuiltInAnalyzer || analyzer.IsWorkspaceDiagnosticAnalyzer() || analyzer.IsCompilerAnalyzer(); public static bool IsOpenFileOnly(this DiagnosticAnalyzer analyzer, OptionSet options) => analyzer is IBuiltInAnalyzer builtInAnalyzer && builtInAnalyzer.OpenFileOnly(options); public static ReportDiagnostic GetEffectiveSeverity(this DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? descriptor.DefaultSeverity.ToReportDiagnostic() : descriptor.GetEffectiveSeverity(options); } public static (string analyzerId, VersionStamp version) GetAnalyzerIdAndVersion(this DiagnosticAnalyzer analyzer) { // Get the unique ID for given diagnostic analyzer. // note that we also put version stamp so that we can detect changed analyzer. var typeInfo = analyzer.GetType().GetTypeInfo(); return (analyzer.GetAnalyzerId(), GetAnalyzerVersion(typeInfo.Assembly.Location)); } public static string GetAnalyzerAssemblyName(this DiagnosticAnalyzer analyzer) => analyzer.GetType().Assembly.GetName().Name ?? throw ExceptionUtilities.Unreachable; public static OptionSet GetAnalyzerOptionSet(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionSetAsync = GetAnalyzerOptionSetAsync(analyzerOptions, syntaxTree, cancellationToken); if (optionSetAsync.IsCompleted) return optionSetAsync.Result; return optionSetAsync.AsTask().GetAwaiter().GetResult(); } public static async ValueTask<OptionSet> GetAnalyzerOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var configOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); #pragma warning disable CS0612 // Type or member is obsolete var optionSet = await GetDocumentOptionSetAsync(analyzerOptions, syntaxTree, cancellationToken).ConfigureAwait(false); #pragma warning restore CS0612 // Type or member is obsolete return new AnalyzerConfigOptionSet(configOptions, optionSet); } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, ILanguageSpecificOption<T> option, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync<T>(analyzerOptions, option, language: null, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) return optionAsync.Result; return optionAsync.AsTask().GetAwaiter().GetResult(); } public static T GetOption<T>(this AnalyzerOptions analyzerOptions, IPerLanguageOption<T> option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { var optionAsync = GetOptionAsync<T>(analyzerOptions, option, language, syntaxTree, cancellationToken); if (optionAsync.IsCompleted) return optionAsync.Result; return optionAsync.AsTask().GetAwaiter().GetResult(); } public static async ValueTask<T> GetOptionAsync<T>(this AnalyzerOptions analyzerOptions, IOption option, string? language, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (analyzerOptions.TryGetEditorConfigOption<T>(option, syntaxTree, out var value)) { return value; } #pragma warning disable CS0612 // Type or member is obsolete var optionSet = await analyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken).ConfigureAwait(false); #pragma warning restore CS0612 // Type or member is obsolete if (optionSet != null) { value = optionSet.GetOption<T>(new OptionKey(option, language)); } return value ?? (T)option.DefaultValue!; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public static ValueTask<OptionSet?> GetDocumentOptionSetAsync(this AnalyzerOptions analyzerOptions, SyntaxTree syntaxTree, CancellationToken cancellationToken) { if (analyzerOptions is not WorkspaceAnalyzerOptions workspaceAnalyzerOptions) { return ValueTaskFactory.FromResult((OptionSet?)null); } return workspaceAnalyzerOptions.GetDocumentOptionSetAsync(syntaxTree, cancellationToken); } /// <summary> /// Create a diagnostic for exception thrown by the given analyzer. /// </summary> /// <remarks> /// Keep this method in sync with "AnalyzerExecutor.CreateAnalyzerExceptionDiagnostic". /// </remarks> internal static Diagnostic CreateAnalyzerExceptionDiagnostic(DiagnosticAnalyzer analyzer, Exception e) { var analyzerName = analyzer.ToString(); // TODO: It is not ideal to create a new descriptor per analyzer exception diagnostic instance. // However, until we add a LongMessage field to the Diagnostic, we are forced to park the instance specific description onto the Descriptor's Description field. // This requires us to create a new DiagnosticDescriptor instance per diagnostic instance. var descriptor = new DiagnosticDescriptor(AnalyzerExceptionDiagnosticId, title: FeaturesResources.User_Diagnostic_Analyzer_Failure, messageFormat: FeaturesResources.Analyzer_0_threw_an_exception_of_type_1_with_message_2, description: string.Format(FeaturesResources.Analyzer_0_threw_the_following_exception_colon_1, analyzerName, e.CreateDiagnosticDescription()), category: AnalyzerExceptionDiagnosticCategory, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.AnalyzerException); return Diagnostic.Create(descriptor, Location.None, analyzerName, e.GetType(), e.Message); } private static VersionStamp GetAnalyzerVersion(string path) { if (path == null || !File.Exists(path)) { return VersionStamp.Default; } return VersionStamp.Create(File.GetLastWriteTimeUtc(path)); } public static DiagnosticData CreateAnalyzerLoadFailureDiagnostic(AnalyzerLoadFailureEventArgs e, string fullPath, ProjectId? projectId, string? language) { static string GetLanguageSpecificId(string? language, string noLanguageId, string csharpId, string vbId) => language == null ? noLanguageId : (language == LanguageNames.CSharp) ? csharpId : vbId; string id, messageFormat, message; switch (e.ErrorCode) { case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToLoadAnalyzer: id = GetLanguageSpecificId(language, WRN_UnableToLoadAnalyzerId, WRN_UnableToLoadAnalyzerIdCS, WRN_UnableToLoadAnalyzerIdVB); messageFormat = FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1; message = string.Format(FeaturesResources.Unable_to_load_Analyzer_assembly_0_colon_1, fullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer: id = GetLanguageSpecificId(language, WRN_AnalyzerCannotBeCreatedId, WRN_AnalyzerCannotBeCreatedIdCS, WRN_AnalyzerCannotBeCreatedIdVB); messageFormat = FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2; message = string.Format(FeaturesResources.An_instance_of_analyzer_0_cannot_be_created_from_1_colon_2, e.TypeName, fullPath, e.Message); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.NoAnalyzers: id = GetLanguageSpecificId(language, WRN_NoAnalyzerInAssemblyId, WRN_NoAnalyzerInAssemblyIdCS, WRN_NoAnalyzerInAssemblyIdVB); messageFormat = FeaturesResources.The_assembly_0_does_not_contain_any_analyzers; message = string.Format(FeaturesResources.The_assembly_0_does_not_contain_any_analyzers, fullPath); break; case AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework: id = GetLanguageSpecificId(language, WRN_AnalyzerReferencesNetFrameworkId, WRN_AnalyzerReferencesNetFrameworkIdCS, WRN_AnalyzerReferencesNetFrameworkIdVB); messageFormat = FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework; message = string.Format(FeaturesResources.The_assembly_0_containing_type_1_references_NET_Framework, fullPath, e.TypeName); break; default: throw ExceptionUtilities.UnexpectedValue(e.ErrorCode); } var description = e.Exception.CreateDiagnosticDescription(); return new DiagnosticData( id, FeaturesResources.Roslyn_HostError, message, messageFormat, severity: DiagnosticSeverity.Warning, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: description, warningLevel: 0, projectId: projectId, customTags: ImmutableArray<string>.Empty, properties: ImmutableDictionary<string, string?>.Empty, language: language); } public static void AppendAnalyzerMap(this Dictionary<string, DiagnosticAnalyzer> analyzerMap, IEnumerable<DiagnosticAnalyzer> analyzers) { foreach (var analyzer in analyzers) { // user might have included exact same analyzer twice as project analyzers explicitly. we consider them as one analyzerMap[analyzer.GetAnalyzerId()] = analyzer; } } public static IEnumerable<AnalyzerPerformanceInfo> ToAnalyzerPerformanceInfo(this IDictionary<DiagnosticAnalyzer, AnalyzerTelemetryInfo> analysisResult, DiagnosticAnalyzerInfoCache analyzerInfo) => analysisResult.Select(kv => new AnalyzerPerformanceInfo(kv.Key.GetAnalyzerId(), analyzerInfo.IsTelemetryCollectionAllowed(kv.Key), kv.Value.ExecutionTime)); public static async Task<CompilationWithAnalyzers?> CreateCompilationWithAnalyzersAsync( Project project, IEnumerable<DiagnosticAnalyzer> analyzers, bool includeSuppressedDiagnostics, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); if (compilation == null) { // project doesn't support compilation return null; } // Create driver that holds onto compilation and associated analyzers var filteredAnalyzers = analyzers.Where(a => !a.IsWorkspaceDiagnosticAnalyzer()).ToImmutableArrayOrEmpty(); // PERF: there is no analyzers for this compilation. // compilationWithAnalyzer will throw if it is created with no analyzers which is perf optimization. if (filteredAnalyzers.IsEmpty) { return null; } Contract.ThrowIfFalse(project.SupportsCompilation); AssertCompilation(project, compilation); // in IDE, we always set concurrentAnalysis == false otherwise, we can get into thread starvation due to // async being used with synchronous blocking concurrency. var analyzerOptions = new CompilationWithAnalyzersOptions( options: new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution), onAnalyzerException: null, analyzerExceptionFilter: GetAnalyzerExceptionFilter(), concurrentAnalysis: false, logAnalyzerExecutionTime: true, reportSuppressedDiagnostics: includeSuppressedDiagnostics); // Create driver that holds onto compilation and associated analyzers return compilation.WithAnalyzers(filteredAnalyzers, analyzerOptions); Func<Exception, bool> GetAnalyzerExceptionFilter() { return ex => { if (ex is not OperationCanceledException && project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException)) { // report telemetry FatalError.ReportAndPropagate(ex); // force fail fast (the host might not crash when reporting telemetry): FailFast.OnFatalException(ex); } return true; }; } } [Conditional("DEBUG")] private static void AssertCompilation(Project project, Compilation compilation1) { // given compilation must be from given project. Contract.ThrowIfFalse(project.TryGetCompilation(out var compilation2)); Contract.ThrowIfFalse(compilation1 == compilation2); } public static async Task<ImmutableArray<Diagnostic>> ComputeDocumentDiagnosticAnalyzerDiagnosticsAsync( DocumentDiagnosticAnalyzer analyzer, Document document, AnalysisKind kind, Compilation? compilation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ImmutableArray<Diagnostic> diagnostics; try { var analyzeAsync = kind switch { AnalysisKind.Syntax => analyzer.AnalyzeSyntaxAsync(document, cancellationToken), AnalysisKind.Semantic => analyzer.AnalyzeSemanticsAsync(document, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(kind), }; diagnostics = (await analyzeAsync.ConfigureAwait(false)).NullToEmpty(); #if DEBUG // since all DocumentDiagnosticAnalyzers are from internal users, we only do debug check. also this can be expensive at runtime // since it requires await. if we find any offender through NFW, we should be able to fix those since all those should // from intern teams. await VerifyDiagnosticLocationsAsync(diagnostics, document.Project, cancellationToken).ConfigureAwait(false); #endif } catch (Exception e) when (!IsCanceled(e, cancellationToken)) { diagnostics = ImmutableArray.Create(CreateAnalyzerExceptionDiagnostic(analyzer, e)); } if (compilation != null) { diagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).ToImmutableArrayOrEmpty(); } return diagnostics; } public static async Task<ImmutableArray<Diagnostic>> ComputeProjectDiagnosticAnalyzerDiagnosticsAsync( ProjectDiagnosticAnalyzer analyzer, Project project, Compilation? compilation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); ImmutableArray<Diagnostic> diagnostics; try { diagnostics = (await analyzer.AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false)).NullToEmpty(); #if DEBUG // since all ProjectDiagnosticAnalyzers are from internal users, we only do debug check. also this can be expensive at runtime // since it requires await. if we find any offender through NFW, we should be able to fix those since all those should // from intern teams. await VerifyDiagnosticLocationsAsync(diagnostics, project, cancellationToken).ConfigureAwait(false); #endif } catch (Exception e) when (!IsCanceled(e, cancellationToken)) { diagnostics = ImmutableArray.Create(CreateAnalyzerExceptionDiagnostic(analyzer, e)); } // Apply filtering from compilation options (source suppressions, ruleset, etc.) if (compilation != null) { diagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnostics, compilation).ToImmutableArrayOrEmpty(); } return diagnostics; } private static bool IsCanceled(Exception ex, CancellationToken cancellationToken) => (ex as OperationCanceledException)?.CancellationToken == cancellationToken; #if DEBUG private static async Task VerifyDiagnosticLocationsAsync(ImmutableArray<Diagnostic> diagnostics, Project project, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { await VerifyDiagnosticLocationAsync(diagnostic.Id, diagnostic.Location).ConfigureAwait(false); if (diagnostic.AdditionalLocations != null) { foreach (var location in diagnostic.AdditionalLocations) { await VerifyDiagnosticLocationAsync(diagnostic.Id, location).ConfigureAwait(false); } } } async Task VerifyDiagnosticLocationAsync(string id, Location location) { switch (location.Kind) { case LocationKind.None: case LocationKind.MetadataFile: case LocationKind.XmlFile: // ignore these kinds break; case LocationKind.SourceFile: { RoslynDebug.Assert(location.SourceTree != null); if (project.GetDocument(location.SourceTree) == null) { // Disallow diagnostics with source locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_in_file_1_which_is_not_part_of_the_compilation_being_analyzed, id, location.SourceTree.FilePath), "diagnostic"); } if (location.SourceSpan.End > location.SourceTree.Length) { // Disallow diagnostics with source locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file, id, location.SourceSpan, location.SourceTree.FilePath), "diagnostic"); } } break; case LocationKind.ExternalFile: { var filePath = location.GetLineSpan().Path; var document = TryGetDocumentWithFilePath(filePath); if (document == null) { // this is not a roslyn file. we don't care about this file. return; } // this can be potentially expensive since it will load text if it is not already loaded. // but, this text is most likely already loaded since producer of this diagnostic (Document/ProjectDiagnosticAnalyzers) // should have loaded it to produce the diagnostic at the first place. once loaded, it should stay in memory until // project cache goes away. when text is already there, await should return right away. var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (location.SourceSpan.End > text.Length) { // Disallow diagnostics with locations outside this project. throw new ArgumentException(string.Format(FeaturesResources.Reported_diagnostic_0_has_a_source_location_1_in_file_2_which_is_outside_of_the_given_file, id, location.SourceSpan, filePath), "diagnostic"); } } break; default: throw ExceptionUtilities.Unreachable; } } Document? TryGetDocumentWithFilePath(string path) { foreach (var documentId in project.Solution.GetDocumentIdsWithFilePath(path)) { if (documentId.ProjectId == project.Id) { return project.GetDocument(documentId); } } return null; } } #endif public static IEnumerable<DiagnosticData> ConvertToLocalDiagnostics(this IEnumerable<Diagnostic> diagnostics, TextDocument targetTextDocument, TextSpan? span = null) { foreach (var diagnostic in diagnostics) { if (!IsReportedInDocument(diagnostic, targetTextDocument)) { continue; } if (span.HasValue && !span.Value.IntersectsWith(diagnostic.Location.SourceSpan)) { continue; } yield return DiagnosticData.Create(diagnostic, targetTextDocument); } static bool IsReportedInDocument(Diagnostic diagnostic, TextDocument targetTextDocument) { if (diagnostic.Location.SourceTree != null) { return targetTextDocument.Project.GetDocument(diagnostic.Location.SourceTree) == targetTextDocument; } else if (diagnostic.Location.Kind == LocationKind.ExternalFile) { var lineSpan = diagnostic.Location.GetLineSpan(); var documentIds = targetTextDocument.Project.Solution.GetDocumentIdsWithFilePath(lineSpan.Path); return documentIds.Any(id => id == targetTextDocument.Id); } return false; } } #if DEBUG internal static bool AreEquivalent(Diagnostic[] diagnosticsA, Diagnostic[] diagnosticsB) { var set = new HashSet<Diagnostic>(diagnosticsA, DiagnosticComparer.Instance); return set.SetEquals(diagnosticsB); } private sealed class DiagnosticComparer : IEqualityComparer<Diagnostic?> { internal static readonly DiagnosticComparer Instance = new(); public bool Equals(Diagnostic? x, Diagnostic? y) { if (x is null) return y is null; else if (y is null) return false; return x.Id == y.Id && x.Location == y.Location; } public int GetHashCode(Diagnostic? obj) { if (obj is null) return 0; return Hash.Combine(obj.Id.GetHashCode(), obj.Location.GetHashCode()); } } #endif } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/CSharpTest/AddUsing/AbstractAddUsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.AddImport; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Remote.Testing; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { public abstract class AbstractAddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected AbstractAddUsingTests(ITestOutputHelper logger = null) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAddImportCodeFixProvider()); private protected OptionsCollection SeparateGroups => Option(GenerationOptions.SeparateImportDirectiveGroups, true); internal async Task TestAsync( string initialMarkup, string expectedMarkup, TestHost testHost, int index = 0, CodeActionPriority? priority = null, OptionsCollection options = null) { await TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters: new TestParameters(options: options, testHost: testHost, priority: priority)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.AddImport; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Remote.Testing; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing { public abstract class AbstractAddUsingTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { protected AbstractAddUsingTests(ITestOutputHelper logger = null) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpAddImportCodeFixProvider()); private protected OptionsCollection SeparateGroups => Option(GenerationOptions.SeparateImportDirectiveGroups, true); internal async Task TestAsync( string initialMarkup, string expectedMarkup, TestHost testHost, int index = 0, CodeActionPriority? priority = null, OptionsCollection options = null) { await TestInRegularAndScript1Async( initialMarkup, expectedMarkup, index, parameters: new TestParameters(options: options, testHost: testHost, priority: priority)); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol_GroupClass.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class SourceNamedTypeSymbol Protected Overrides Sub AddGroupClassMembersIfNeeded(membersBuilder As MembersAndInitializersBuilder, diagnostics As BindingDiagnosticBag) ' For reference, see Bindable::IsMyGroupCollection and Bindable::CrackAttributesOnAllSymbolsInContainer in native code. If Me.TypeKind = TypeKind.Class AndAlso Not Me.IsGenericType Then Dim binder As Binder = Nothing Dim attributeSyntax As AttributeSyntax = Nothing Dim attributeData As VisualBasicAttributeData = GetMyGroupCollectionAttributeData(diagnostics, binder, attributeSyntax) If attributeData IsNot Nothing Then ' Ok, this looks like a group class. Let's inspect the attribute data (Attribute::CrackArgBlob). ' Attribute arguments are comma-separated lists. Dim separatorComma = {","c} Dim separatorDot = {"."c} Dim baseTypeNames() As String = If(attributeData.GetConstructorArgument(Of String)(0, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Dim createMethods() As String = If(attributeData.GetConstructorArgument(Of String)(1, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Dim disposeMethods() As String = If(attributeData.GetConstructorArgument(Of String)(2, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) ' DefaultInstanceAliases are respected only for attributes applied in MyTemplate. Dim defaultInstances() As String If attributeSyntax.SyntaxTree.IsMyTemplate Then defaultInstances = If(attributeData.GetConstructorArgument(Of String)(3, Microsoft.CodeAnalysis.SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Else defaultInstances = Array.Empty(Of String)() End If ' Types matching each name in baseTypeNames will be grouped together in the builder below and groups will be separated by Nothing item. ' See comment inside the loop about why there could be more than one. Dim baseTypes As ArrayBuilder(Of NamedTypeSymbol) = ArrayBuilder(Of NamedTypeSymbol).GetInstance() Dim haveBaseTypes As Boolean = False For i As Integer = 0 To Math.Min(baseTypeNames.Length, createMethods.Length) - 1 baseTypeNames(i) = baseTypeNames(i).Trim() createMethods(i) = createMethods(i).Trim() If baseTypeNames(i).Length = 0 OrElse createMethods(i).Length = 0 Then ' This might feel strange, but native compiler stops processing arguments ' as soon as it encounters an empty base type name or create method name Exit For Else If i < disposeMethods.Length Then disposeMethods(i) = disposeMethods(i).Trim() End If If i < defaultInstances.Length Then defaultInstances(i) = defaultInstances(i).Trim() End If ' See if we can locate the base class this group class is associated with. This might feel strange, ' but native compiler does the match by fully qualified name without generic parameters, therefore we might ' find more than one base type from different assemblies or types with different arities, all are valid candidates. FindGroupClassBaseTypes(baseTypeNames(i).Split(separatorDot, StringSplitOptions.None), DeclaringCompilation.GlobalNamespace, 0, baseTypes) If Not haveBaseTypes AndAlso baseTypes.Count > 0 AndAlso baseTypes.Last() IsNot Nothing Then haveBaseTypes = True End If End If baseTypes.Add(Nothing) Next If haveBaseTypes Then ' Now, iterate over all top level types declared in this module and pick those ' inheriting from the bases we found (Bindable::ScanAndLoadMyGroupCollectionMembers). Dim collectionTypes = ArrayBuilder(Of KeyValuePair(Of NamedTypeSymbol, Integer)).GetInstance() GetMyGroupCollectionTypes(Me.ContainingModule.GlobalNamespace, baseTypes, binder, collectionTypes) If collectionTypes.Count > 0 Then ' See Bindable::GenSyntheticMyGroupCollectionProperties ' sort members to handle simple name clashes. Having all the classes with the same simple name ' grouped together helps decide in one step if mangling is necessary. ' It is only a gain of O(n*n) -> O(n*log(n)) collectionTypes.Sort(GroupCollectionComparer.Singleton) For i As Integer = 0 To collectionTypes.Count - 1 Dim current As KeyValuePair(Of NamedTypeSymbol, Integer) = collectionTypes(i) ' members with the same simple name are grouped together. ' if two adjacent members with the same simple name then use name mangling Dim mangleNames As Boolean = (i > 0 AndAlso IdentifierComparison.Equals(current.Key.Name, collectionTypes(i - 1).Key.Name)) OrElse (i < collectionTypes.Count - 1 AndAlso IdentifierComparison.Equals(current.Key.Name, collectionTypes(i + 1).Key.Name)) AddSyntheticMyGroupCollectionProperty(current.Key, mangleNames, createMethods(current.Value), If(current.Value < disposeMethods.Length, disposeMethods(current.Value), ""), If(current.Value < defaultInstances.Length, defaultInstances(current.Value), ""), membersBuilder, binder, attributeSyntax, diagnostics) Next End If collectionTypes.Free() End If baseTypes.Free() End If End If End Sub Private Function GetMyGroupCollectionAttributeData(diagnostics As BindingDiagnosticBag, <Out> ByRef binder As Binder, <Out> ByRef attributeSyntax As AttributeSyntax) As VisualBasicAttributeData ' Calling GetAttributes() here is likely to get us in a cycle. Also, we want this function to be ' as cheap as possible, it is called for every class and we don't want to bind all attributes ' attached to the declaration (even when it doesn't cause a cycle) before we able to create symbol's ' members. So, we will have to manually bind only those attributes that potentially could be ' MyGroupCollectionAttribute, by examining syntax ourselves. Dim attributeLists As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) = GetAttributeDeclarations() Dim attributeData As VisualBasicAttributeData = Nothing For Each list As SyntaxList(Of AttributeListSyntax) In attributeLists If list.Any() Then binder = GetAttributeBinder(list, ContainingSourceModule) Dim quickChecker As QuickAttributeChecker = binder.QuickAttributeChecker For Each attrList In list For Each attr In attrList.Attributes If (quickChecker.CheckAttribute(attr) And QuickAttributes.MyGroupCollection) <> 0 Then ' This attribute syntax might be an application of MyGroupCollectionAttribute. ' Let's bind it. Dim attributeType As NamedTypeSymbol = Binder.BindAttributeType(binder, attr, Me, BindingDiagnosticBag.Discarded) If Not attributeType.IsErrorType() Then If VisualBasicAttributeData.IsTargetEarlyAttribute(attributeType, attr, AttributeDescription.MyGroupCollectionAttribute) Then ' Calling GetAttribute can still get us into cycle if MyGroupCollectionAttribute is applied to itself. If attributeType Is Me Then binder.ReportDiagnostic(diagnostics, attr, ERRID.ERR_MyGroupCollectionAttributeCycle) Debug.Assert(attributeData Is Nothing) GoTo DoneWithBindingAttributes End If ' Or if any argument expression refers to a member of this type. Therefore, as a simple solution, ' we will allow only literals as the arguments. For Each argumentSyntax As ArgumentSyntax In attr.ArgumentList.Arguments Dim expression As ExpressionSyntax Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument expression = DirectCast(argumentSyntax, SimpleArgumentSyntax).Expression Case SyntaxKind.OmittedArgument expression = Nothing Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select If expression IsNot Nothing AndAlso Not TypeOf expression Is LiteralExpressionSyntax Then binder.ReportDiagnostic(diagnostics, expression, ERRID.ERR_LiteralExpected) attributeData = Nothing GoTo DoneWithBindingAttributes End If Next Dim generatedDiagnostics As Boolean = False Dim data As VisualBasicAttributeData = (New EarlyWellKnownAttributeBinder(Me, binder)).GetAttribute(attr, attributeType, generatedDiagnostics) If Not data.HasErrors AndAlso Not generatedDiagnostics AndAlso data.IsTargetAttribute(Me, AttributeDescription.MyGroupCollectionAttribute) Then ' Looks like we've found MyGroupCollectionAttribute If attributeData IsNot Nothing Then ' Ambiguity, the attribute cannot be applied multiple times. Let's ignore all of them, ' an error about multiple applications will be reported later, when all attributes are ' bound and validated. attributeData = Nothing GoTo DoneWithBindingAttributes End If attributeData = data attributeSyntax = attr End If End If End If End If Next Next End If Next DoneWithBindingAttributes: If attributeData Is Nothing Then binder = Nothing attributeSyntax = Nothing End If Return attributeData End Function Private Shared Sub FindGroupClassBaseTypes(nameParts() As String, current As NamespaceOrTypeSymbol, nextPart As Integer, candidates As ArrayBuilder(Of NamedTypeSymbol)) ' Bindable::FindBaseInMyGroupCollection If nextPart = nameParts.Length Then If current.Kind = SymbolKind.NamedType Then Dim named = DirectCast(current, NamedTypeSymbol) If named.TypeKind = TypeKind.Class AndAlso Not named.IsNotInheritable Then candidates.Add(named) End If End If Return End If Dim name As String = nameParts(nextPart) nextPart += 1 For Each member As Symbol In current.GetMembers(name) Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType FindGroupClassBaseTypes(nameParts, DirectCast(member, NamespaceOrTypeSymbol), nextPart, candidates) End Select Next End Sub Private Shared Sub GetMyGroupCollectionTypes( ns As NamespaceSymbol, baseTypes As ArrayBuilder(Of NamedTypeSymbol), binder As Binder, collectionTypes As ArrayBuilder(Of KeyValuePair(Of NamedTypeSymbol, Integer)) ) For Each member As Symbol In ns.GetMembersUnordered() Select Case member.Kind Case SymbolKind.NamedType Dim named = TryCast(member, SourceNamedTypeSymbol) ' See Bindable::ScanAndLoadMyGroupCollectionMembers, Bindable::CanBeMyGroupCollectionMember ' CONSIDER: The IsAccessible check is probably redundant because top level types are always accessible within the same module. ' We can remove it if it becomes a perf issue. If named IsNot Nothing AndAlso Not named.IsImplicitlyDeclared AndAlso named.TypeKind = TypeKind.Class AndAlso Not named.IsGenericType AndAlso Not named.IsMustInherit AndAlso binder.IsAccessible(named, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Dim matchingItem As Integer = FindBaseInMyGroupCollection(named, baseTypes) If matchingItem >= 0 AndAlso MyGroupCollectionCandidateHasPublicParameterlessConstructor(named) Then collectionTypes.Add(New KeyValuePair(Of NamedTypeSymbol, Integer)(named, matchingItem)) End If End If Case SymbolKind.Namespace GetMyGroupCollectionTypes(DirectCast(member, NamespaceSymbol), baseTypes, binder, collectionTypes) End Select Next End Sub Private Shared Function FindBaseInMyGroupCollection(classType As NamedTypeSymbol, bases As ArrayBuilder(Of NamedTypeSymbol)) As Integer ' See Bindable::FindBaseInMyGroupCollection ' Names in the MyGroupCollectionAttribute are matched from left to right to bases from most derived to the least derived. classType = classType.BaseTypeNoUseSiteDiagnostics While classType IsNot Nothing AndAlso Not classType.IsObjectType() Dim result As Integer = 0 For Each candidate As NamedTypeSymbol In bases If candidate Is Nothing Then ' This means that we are switching to the next item in the comma-separated list of base type names. result += 1 ElseIf classType.OriginalDefinition Is candidate Then Return result End If Next classType = classType.BaseTypeNoUseSiteDiagnostics End While Return -1 ' Haven't found a match. End Function Private Shared Function MyGroupCollectionCandidateHasPublicParameterlessConstructor(candidate As SourceNamedTypeSymbol) As Boolean ' Simply calling HasPublicParameterlessConstructor might get us in a cycle. If candidate.MembersHaveBeenCreated Then Return HasPublicParameterlessConstructor(candidate) Else Return candidate.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() End If End Function #If DEBUG Then Protected Overrides Sub VerifyMembers() If Me.TypeKind = TypeKind.Class Then Debug.Assert(MembersHaveBeenCreated) Debug.Assert(HasPublicParameterlessConstructor(Me) = InferFromSyntaxIfClassWillHavePublicParameterlessConstructor()) End If End Sub #End If Friend Function InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() As Boolean Debug.Assert(Me.TypeKind = TypeKind.Class) Dim diagnostics = DiagnosticBag.GetInstance() Dim haveInstanceConstructor As Boolean = False For Each syntaxRef In SyntaxReferences Dim node = syntaxRef.GetSyntax() ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) Dim typeBlock = DirectCast(node, TypeBlockSyntax) For Each memberSyntax In typeBlock.Members Dim constructorSyntax As SubNewStatementSyntax Select Case memberSyntax.Kind Case SyntaxKind.ConstructorBlock constructorSyntax = DirectCast(memberSyntax, ConstructorBlockSyntax).SubNewStatement Case SyntaxKind.SubNewStatement constructorSyntax = DirectCast(memberSyntax, SubNewStatementSyntax) Case Else constructorSyntax = Nothing End Select If constructorSyntax IsNot Nothing Then Dim modifiers As SourceMemberFlags = SourceMethodSymbol.DecodeConstructorModifiers(constructorSyntax.Modifiers, Me, binder, diagnostics).AllFlags If (modifiers And SourceMemberFlags.Shared) = 0 Then If constructorSyntax.ParameterList Is Nothing OrElse constructorSyntax.ParameterList.Parameters.Count = 0 Then diagnostics.Free() Return (modifiers And SourceMemberFlags.AccessibilityMask) = SourceMemberFlags.AccessibilityPublic End If haveInstanceConstructor = True End If End If Next Next diagnostics.Free() Return Not haveInstanceConstructor AndAlso Not Me.IsMustInherit End Function ''' <summary> ''' Used to sort types - members of group collection. ''' </summary> Private Class GroupCollectionComparer Implements IComparer(Of KeyValuePair(Of NamedTypeSymbol, Integer)) Public Shared ReadOnly Singleton As New GroupCollectionComparer Private Sub New() End Sub Public Function Compare(x As KeyValuePair(Of NamedTypeSymbol, Integer), y As KeyValuePair(Of NamedTypeSymbol, Integer)) As Integer Implements IComparer(Of KeyValuePair(Of NamedTypeSymbol, Integer)).Compare Return IdentifierComparison.Compare(x.Key.Name, y.Key.Name) End Function End Class Private Sub AddSyntheticMyGroupCollectionProperty( targetType As NamedTypeSymbol, mangleNames As Boolean, createMethod As String, disposeMethod As String, defaultInstanceAlias As String, membersBuilder As MembersAndInitializersBuilder, binder As Binder, attributeSyntax As AttributeSyntax, diagnostics As BindingDiagnosticBag ) Dim propertyName As String If mangleNames Then propertyName = targetType.ToDisplayString() propertyName = propertyName.Replace("."c, "_"c) Else propertyName = targetType.Name End If Dim fieldName As String = "m_" & propertyName ' For now let reject any clash. The new member is a synthetic property and no overloads or other members with the same name should ' be allowed Dim conflictsWith As Symbol = Nothing Dim nestedTypes = GetTypeMembersDictionary() Dim isWinMd = Me.IsCompilationOutputWinMdObj() If ConflictsWithExistingMemberOrType(propertyName, membersBuilder, nestedTypes, conflictsWith) OrElse ConflictsWithExistingMemberOrType(binder.GetAccessorName(propertyName, MethodKind.PropertyGet, False), membersBuilder, nestedTypes, conflictsWith) OrElse (disposeMethod.Length > 0 AndAlso ConflictsWithExistingMemberOrType(binder.GetAccessorName(propertyName, MethodKind.PropertySet, isWinMd), membersBuilder, nestedTypes, conflictsWith)) OrElse ConflictsWithExistingMemberOrType(fieldName, membersBuilder, nestedTypes, conflictsWith) Then binder.ReportDiagnostic(diagnostics, attributeSyntax, ERRID.ERR_PropertyNameConflictInMyCollection, conflictsWith, targetType) Return End If Dim prop As New SynthesizedMyGroupCollectionPropertySymbol(Me, attributeSyntax, propertyName, fieldName, targetType, createMethod, disposeMethod, defaultInstanceAlias) AddMember(prop.AssociatedField, binder, membersBuilder, omitDiagnostics:=True) AddMember(prop, binder, membersBuilder, omitDiagnostics:=True) AddMember(prop.GetMethod, binder, membersBuilder, omitDiagnostics:=True) If prop.SetMethod IsNot Nothing Then AddMember(prop.SetMethod, binder, membersBuilder, omitDiagnostics:=True) End If End Sub Private Shared Function ConflictsWithExistingMemberOrType( name As String, membersBuilder As MembersAndInitializersBuilder, nestedTypes As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)), <Out> ByRef conflictsWith As Symbol ) As Boolean Dim members As ArrayBuilder(Of Symbol) = Nothing Dim types As ImmutableArray(Of NamedTypeSymbol) = Nothing If membersBuilder.Members.TryGetValue(name, members) Then conflictsWith = members(0) ElseIf nestedTypes.TryGetValue(name, types) Then conflictsWith = types(0) Else conflictsWith = Nothing End If Return conflictsWith IsNot Nothing End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend Class SourceNamedTypeSymbol Protected Overrides Sub AddGroupClassMembersIfNeeded(membersBuilder As MembersAndInitializersBuilder, diagnostics As BindingDiagnosticBag) ' For reference, see Bindable::IsMyGroupCollection and Bindable::CrackAttributesOnAllSymbolsInContainer in native code. If Me.TypeKind = TypeKind.Class AndAlso Not Me.IsGenericType Then Dim binder As Binder = Nothing Dim attributeSyntax As AttributeSyntax = Nothing Dim attributeData As VisualBasicAttributeData = GetMyGroupCollectionAttributeData(diagnostics, binder, attributeSyntax) If attributeData IsNot Nothing Then ' Ok, this looks like a group class. Let's inspect the attribute data (Attribute::CrackArgBlob). ' Attribute arguments are comma-separated lists. Dim separatorComma = {","c} Dim separatorDot = {"."c} Dim baseTypeNames() As String = If(attributeData.GetConstructorArgument(Of String)(0, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Dim createMethods() As String = If(attributeData.GetConstructorArgument(Of String)(1, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Dim disposeMethods() As String = If(attributeData.GetConstructorArgument(Of String)(2, SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) ' DefaultInstanceAliases are respected only for attributes applied in MyTemplate. Dim defaultInstances() As String If attributeSyntax.SyntaxTree.IsMyTemplate Then defaultInstances = If(attributeData.GetConstructorArgument(Of String)(3, Microsoft.CodeAnalysis.SpecialType.System_String), "").Split(separatorComma, StringSplitOptions.None) Else defaultInstances = Array.Empty(Of String)() End If ' Types matching each name in baseTypeNames will be grouped together in the builder below and groups will be separated by Nothing item. ' See comment inside the loop about why there could be more than one. Dim baseTypes As ArrayBuilder(Of NamedTypeSymbol) = ArrayBuilder(Of NamedTypeSymbol).GetInstance() Dim haveBaseTypes As Boolean = False For i As Integer = 0 To Math.Min(baseTypeNames.Length, createMethods.Length) - 1 baseTypeNames(i) = baseTypeNames(i).Trim() createMethods(i) = createMethods(i).Trim() If baseTypeNames(i).Length = 0 OrElse createMethods(i).Length = 0 Then ' This might feel strange, but native compiler stops processing arguments ' as soon as it encounters an empty base type name or create method name Exit For Else If i < disposeMethods.Length Then disposeMethods(i) = disposeMethods(i).Trim() End If If i < defaultInstances.Length Then defaultInstances(i) = defaultInstances(i).Trim() End If ' See if we can locate the base class this group class is associated with. This might feel strange, ' but native compiler does the match by fully qualified name without generic parameters, therefore we might ' find more than one base type from different assemblies or types with different arities, all are valid candidates. FindGroupClassBaseTypes(baseTypeNames(i).Split(separatorDot, StringSplitOptions.None), DeclaringCompilation.GlobalNamespace, 0, baseTypes) If Not haveBaseTypes AndAlso baseTypes.Count > 0 AndAlso baseTypes.Last() IsNot Nothing Then haveBaseTypes = True End If End If baseTypes.Add(Nothing) Next If haveBaseTypes Then ' Now, iterate over all top level types declared in this module and pick those ' inheriting from the bases we found (Bindable::ScanAndLoadMyGroupCollectionMembers). Dim collectionTypes = ArrayBuilder(Of KeyValuePair(Of NamedTypeSymbol, Integer)).GetInstance() GetMyGroupCollectionTypes(Me.ContainingModule.GlobalNamespace, baseTypes, binder, collectionTypes) If collectionTypes.Count > 0 Then ' See Bindable::GenSyntheticMyGroupCollectionProperties ' sort members to handle simple name clashes. Having all the classes with the same simple name ' grouped together helps decide in one step if mangling is necessary. ' It is only a gain of O(n*n) -> O(n*log(n)) collectionTypes.Sort(GroupCollectionComparer.Singleton) For i As Integer = 0 To collectionTypes.Count - 1 Dim current As KeyValuePair(Of NamedTypeSymbol, Integer) = collectionTypes(i) ' members with the same simple name are grouped together. ' if two adjacent members with the same simple name then use name mangling Dim mangleNames As Boolean = (i > 0 AndAlso IdentifierComparison.Equals(current.Key.Name, collectionTypes(i - 1).Key.Name)) OrElse (i < collectionTypes.Count - 1 AndAlso IdentifierComparison.Equals(current.Key.Name, collectionTypes(i + 1).Key.Name)) AddSyntheticMyGroupCollectionProperty(current.Key, mangleNames, createMethods(current.Value), If(current.Value < disposeMethods.Length, disposeMethods(current.Value), ""), If(current.Value < defaultInstances.Length, defaultInstances(current.Value), ""), membersBuilder, binder, attributeSyntax, diagnostics) Next End If collectionTypes.Free() End If baseTypes.Free() End If End If End Sub Private Function GetMyGroupCollectionAttributeData(diagnostics As BindingDiagnosticBag, <Out> ByRef binder As Binder, <Out> ByRef attributeSyntax As AttributeSyntax) As VisualBasicAttributeData ' Calling GetAttributes() here is likely to get us in a cycle. Also, we want this function to be ' as cheap as possible, it is called for every class and we don't want to bind all attributes ' attached to the declaration (even when it doesn't cause a cycle) before we able to create symbol's ' members. So, we will have to manually bind only those attributes that potentially could be ' MyGroupCollectionAttribute, by examining syntax ourselves. Dim attributeLists As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) = GetAttributeDeclarations() Dim attributeData As VisualBasicAttributeData = Nothing For Each list As SyntaxList(Of AttributeListSyntax) In attributeLists If list.Any() Then binder = GetAttributeBinder(list, ContainingSourceModule) Dim quickChecker As QuickAttributeChecker = binder.QuickAttributeChecker For Each attrList In list For Each attr In attrList.Attributes If (quickChecker.CheckAttribute(attr) And QuickAttributes.MyGroupCollection) <> 0 Then ' This attribute syntax might be an application of MyGroupCollectionAttribute. ' Let's bind it. Dim attributeType As NamedTypeSymbol = Binder.BindAttributeType(binder, attr, Me, BindingDiagnosticBag.Discarded) If Not attributeType.IsErrorType() Then If VisualBasicAttributeData.IsTargetEarlyAttribute(attributeType, attr, AttributeDescription.MyGroupCollectionAttribute) Then ' Calling GetAttribute can still get us into cycle if MyGroupCollectionAttribute is applied to itself. If attributeType Is Me Then binder.ReportDiagnostic(diagnostics, attr, ERRID.ERR_MyGroupCollectionAttributeCycle) Debug.Assert(attributeData Is Nothing) GoTo DoneWithBindingAttributes End If ' Or if any argument expression refers to a member of this type. Therefore, as a simple solution, ' we will allow only literals as the arguments. For Each argumentSyntax As ArgumentSyntax In attr.ArgumentList.Arguments Dim expression As ExpressionSyntax Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument expression = DirectCast(argumentSyntax, SimpleArgumentSyntax).Expression Case SyntaxKind.OmittedArgument expression = Nothing Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select If expression IsNot Nothing AndAlso Not TypeOf expression Is LiteralExpressionSyntax Then binder.ReportDiagnostic(diagnostics, expression, ERRID.ERR_LiteralExpected) attributeData = Nothing GoTo DoneWithBindingAttributes End If Next Dim generatedDiagnostics As Boolean = False Dim data As VisualBasicAttributeData = (New EarlyWellKnownAttributeBinder(Me, binder)).GetAttribute(attr, attributeType, generatedDiagnostics) If Not data.HasErrors AndAlso Not generatedDiagnostics AndAlso data.IsTargetAttribute(Me, AttributeDescription.MyGroupCollectionAttribute) Then ' Looks like we've found MyGroupCollectionAttribute If attributeData IsNot Nothing Then ' Ambiguity, the attribute cannot be applied multiple times. Let's ignore all of them, ' an error about multiple applications will be reported later, when all attributes are ' bound and validated. attributeData = Nothing GoTo DoneWithBindingAttributes End If attributeData = data attributeSyntax = attr End If End If End If End If Next Next End If Next DoneWithBindingAttributes: If attributeData Is Nothing Then binder = Nothing attributeSyntax = Nothing End If Return attributeData End Function Private Shared Sub FindGroupClassBaseTypes(nameParts() As String, current As NamespaceOrTypeSymbol, nextPart As Integer, candidates As ArrayBuilder(Of NamedTypeSymbol)) ' Bindable::FindBaseInMyGroupCollection If nextPart = nameParts.Length Then If current.Kind = SymbolKind.NamedType Then Dim named = DirectCast(current, NamedTypeSymbol) If named.TypeKind = TypeKind.Class AndAlso Not named.IsNotInheritable Then candidates.Add(named) End If End If Return End If Dim name As String = nameParts(nextPart) nextPart += 1 For Each member As Symbol In current.GetMembers(name) Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType FindGroupClassBaseTypes(nameParts, DirectCast(member, NamespaceOrTypeSymbol), nextPart, candidates) End Select Next End Sub Private Shared Sub GetMyGroupCollectionTypes( ns As NamespaceSymbol, baseTypes As ArrayBuilder(Of NamedTypeSymbol), binder As Binder, collectionTypes As ArrayBuilder(Of KeyValuePair(Of NamedTypeSymbol, Integer)) ) For Each member As Symbol In ns.GetMembersUnordered() Select Case member.Kind Case SymbolKind.NamedType Dim named = TryCast(member, SourceNamedTypeSymbol) ' See Bindable::ScanAndLoadMyGroupCollectionMembers, Bindable::CanBeMyGroupCollectionMember ' CONSIDER: The IsAccessible check is probably redundant because top level types are always accessible within the same module. ' We can remove it if it becomes a perf issue. If named IsNot Nothing AndAlso Not named.IsImplicitlyDeclared AndAlso named.TypeKind = TypeKind.Class AndAlso Not named.IsGenericType AndAlso Not named.IsMustInherit AndAlso binder.IsAccessible(named, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Dim matchingItem As Integer = FindBaseInMyGroupCollection(named, baseTypes) If matchingItem >= 0 AndAlso MyGroupCollectionCandidateHasPublicParameterlessConstructor(named) Then collectionTypes.Add(New KeyValuePair(Of NamedTypeSymbol, Integer)(named, matchingItem)) End If End If Case SymbolKind.Namespace GetMyGroupCollectionTypes(DirectCast(member, NamespaceSymbol), baseTypes, binder, collectionTypes) End Select Next End Sub Private Shared Function FindBaseInMyGroupCollection(classType As NamedTypeSymbol, bases As ArrayBuilder(Of NamedTypeSymbol)) As Integer ' See Bindable::FindBaseInMyGroupCollection ' Names in the MyGroupCollectionAttribute are matched from left to right to bases from most derived to the least derived. classType = classType.BaseTypeNoUseSiteDiagnostics While classType IsNot Nothing AndAlso Not classType.IsObjectType() Dim result As Integer = 0 For Each candidate As NamedTypeSymbol In bases If candidate Is Nothing Then ' This means that we are switching to the next item in the comma-separated list of base type names. result += 1 ElseIf classType.OriginalDefinition Is candidate Then Return result End If Next classType = classType.BaseTypeNoUseSiteDiagnostics End While Return -1 ' Haven't found a match. End Function Private Shared Function MyGroupCollectionCandidateHasPublicParameterlessConstructor(candidate As SourceNamedTypeSymbol) As Boolean ' Simply calling HasPublicParameterlessConstructor might get us in a cycle. If candidate.MembersHaveBeenCreated Then Return HasPublicParameterlessConstructor(candidate) Else Return candidate.InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() End If End Function #If DEBUG Then Protected Overrides Sub VerifyMembers() If Me.TypeKind = TypeKind.Class Then Debug.Assert(MembersHaveBeenCreated) Debug.Assert(HasPublicParameterlessConstructor(Me) = InferFromSyntaxIfClassWillHavePublicParameterlessConstructor()) End If End Sub #End If Friend Function InferFromSyntaxIfClassWillHavePublicParameterlessConstructor() As Boolean Debug.Assert(Me.TypeKind = TypeKind.Class) Dim diagnostics = DiagnosticBag.GetInstance() Dim haveInstanceConstructor As Boolean = False For Each syntaxRef In SyntaxReferences Dim node = syntaxRef.GetSyntax() ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) Dim typeBlock = DirectCast(node, TypeBlockSyntax) For Each memberSyntax In typeBlock.Members Dim constructorSyntax As SubNewStatementSyntax Select Case memberSyntax.Kind Case SyntaxKind.ConstructorBlock constructorSyntax = DirectCast(memberSyntax, ConstructorBlockSyntax).SubNewStatement Case SyntaxKind.SubNewStatement constructorSyntax = DirectCast(memberSyntax, SubNewStatementSyntax) Case Else constructorSyntax = Nothing End Select If constructorSyntax IsNot Nothing Then Dim modifiers As SourceMemberFlags = SourceMethodSymbol.DecodeConstructorModifiers(constructorSyntax.Modifiers, Me, binder, diagnostics).AllFlags If (modifiers And SourceMemberFlags.Shared) = 0 Then If constructorSyntax.ParameterList Is Nothing OrElse constructorSyntax.ParameterList.Parameters.Count = 0 Then diagnostics.Free() Return (modifiers And SourceMemberFlags.AccessibilityMask) = SourceMemberFlags.AccessibilityPublic End If haveInstanceConstructor = True End If End If Next Next diagnostics.Free() Return Not haveInstanceConstructor AndAlso Not Me.IsMustInherit End Function ''' <summary> ''' Used to sort types - members of group collection. ''' </summary> Private Class GroupCollectionComparer Implements IComparer(Of KeyValuePair(Of NamedTypeSymbol, Integer)) Public Shared ReadOnly Singleton As New GroupCollectionComparer Private Sub New() End Sub Public Function Compare(x As KeyValuePair(Of NamedTypeSymbol, Integer), y As KeyValuePair(Of NamedTypeSymbol, Integer)) As Integer Implements IComparer(Of KeyValuePair(Of NamedTypeSymbol, Integer)).Compare Return IdentifierComparison.Compare(x.Key.Name, y.Key.Name) End Function End Class Private Sub AddSyntheticMyGroupCollectionProperty( targetType As NamedTypeSymbol, mangleNames As Boolean, createMethod As String, disposeMethod As String, defaultInstanceAlias As String, membersBuilder As MembersAndInitializersBuilder, binder As Binder, attributeSyntax As AttributeSyntax, diagnostics As BindingDiagnosticBag ) Dim propertyName As String If mangleNames Then propertyName = targetType.ToDisplayString() propertyName = propertyName.Replace("."c, "_"c) Else propertyName = targetType.Name End If Dim fieldName As String = "m_" & propertyName ' For now let reject any clash. The new member is a synthetic property and no overloads or other members with the same name should ' be allowed Dim conflictsWith As Symbol = Nothing Dim nestedTypes = GetTypeMembersDictionary() Dim isWinMd = Me.IsCompilationOutputWinMdObj() If ConflictsWithExistingMemberOrType(propertyName, membersBuilder, nestedTypes, conflictsWith) OrElse ConflictsWithExistingMemberOrType(binder.GetAccessorName(propertyName, MethodKind.PropertyGet, False), membersBuilder, nestedTypes, conflictsWith) OrElse (disposeMethod.Length > 0 AndAlso ConflictsWithExistingMemberOrType(binder.GetAccessorName(propertyName, MethodKind.PropertySet, isWinMd), membersBuilder, nestedTypes, conflictsWith)) OrElse ConflictsWithExistingMemberOrType(fieldName, membersBuilder, nestedTypes, conflictsWith) Then binder.ReportDiagnostic(diagnostics, attributeSyntax, ERRID.ERR_PropertyNameConflictInMyCollection, conflictsWith, targetType) Return End If Dim prop As New SynthesizedMyGroupCollectionPropertySymbol(Me, attributeSyntax, propertyName, fieldName, targetType, createMethod, disposeMethod, defaultInstanceAlias) AddMember(prop.AssociatedField, binder, membersBuilder, omitDiagnostics:=True) AddMember(prop, binder, membersBuilder, omitDiagnostics:=True) AddMember(prop.GetMethod, binder, membersBuilder, omitDiagnostics:=True) If prop.SetMethod IsNot Nothing Then AddMember(prop.SetMethod, binder, membersBuilder, omitDiagnostics:=True) End If End Sub Private Shared Function ConflictsWithExistingMemberOrType( name As String, membersBuilder As MembersAndInitializersBuilder, nestedTypes As Dictionary(Of String, ImmutableArray(Of NamedTypeSymbol)), <Out> ByRef conflictsWith As Symbol ) As Boolean Dim members As ArrayBuilder(Of Symbol) = Nothing Dim types As ImmutableArray(Of NamedTypeSymbol) = Nothing If membersBuilder.Members.TryGetValue(name, members) Then conflictsWith = members(0) ElseIf nestedTypes.TryGetValue(name, types) Then conflictsWith = types(0) Else conflictsWith = Nothing End If Return conflictsWith IsNot Nothing End Function End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/TestUtilities2/Intellisense/IIntelliSenseTestState.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.IntelliSense Friend Interface IIntelliSenseTestState Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession End Interface 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.IntelliSense Friend Interface IIntelliSenseTestState Property CurrentSignatureHelpPresenterSession As TestSignatureHelpPresenterSession End Interface End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.LocalFunctions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal partial class DefiniteAssignmentPass { internal sealed class LocalFunctionState : AbstractLocalFunctionState { public BitVector ReadVars = BitVector.Empty; public BitVector CapturedMask = BitVector.Null; public BitVector InvertedCapturedMask = BitVector.Null; public LocalFunctionState(LocalState stateFromBottom, LocalState stateFromTop) : base(stateFromBottom, stateFromTop) { } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) => CreateLocalFunctionState(); private LocalFunctionState CreateLocalFunctionState() => new LocalFunctionState( // The bottom state should assume all variables, even new ones, are assigned new LocalState(BitVector.AllSet(variableBySlot.Count), normalizeToBottom: true), UnreachableState()); protected override void VisitLocalFunctionUse( LocalFunctionSymbol localFunc, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { _usedLocalFunctions.Add(localFunc); // Check variables that were read before being definitely assigned. var reads = localFunctionState.ReadVars; // Start at slot 1 (slot 0 just indicates reachability) for (int slot = 1; slot < reads.Capacity; slot++) { if (reads[slot]) { var symbol = variableBySlot[slot].Symbol; CheckIfAssignedDuringLocalFunctionReplay(symbol, syntax, slot); } } base.VisitLocalFunctionUse(localFunc, localFunctionState, syntax, isCall); } /// <summary> /// Check that the given variable is definitely assigned when replaying local function /// reads. If not, produce an error. /// </summary> /// <remarks> /// Specifying the slot manually may be necessary if the symbol is a field, /// in which case <see cref="LocalDataFlowPass{TLocalState, TLocalFunctionState}.VariableSlot(Symbol, int)"/> /// will not know which containing slot to look for. /// </remarks> private void CheckIfAssignedDuringLocalFunctionReplay(Symbol symbol, SyntaxNode node, int slot) { Debug.Assert(!IsConditionalState); if ((object)symbol != null) { NoteRead(symbol); if (this.State.Reachable) { if (slot >= this.State.Assigned.Capacity) { Normalize(ref this.State); } if (slot > 0 && !this.State.IsAssigned(slot)) { // Local functions can "call forward" to after a variable has // been declared but before it has been assigned, so we can never // consider the declaration location when reporting errors. ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, slot, skipIfUseBeforeDeclaration: false); } } } } private void RecordReadInLocalFunction(int slot) { var localFunc = GetNearestLocalFunctionOpt(CurrentSymbol); Debug.Assert(localFunc != null); var usages = GetOrCreateLocalFuncUsages(localFunc); // If this slot is a struct with individually assignable // fields we need to record each field assignment separately, // since some fields may be assigned when this read is replayed VariableIdentifier id = variableBySlot[slot]; var type = id.Symbol.GetTypeOrReturnType().Type; Debug.Assert(!_emptyStructTypeCache.IsEmptyStructType(type)); if (EmptyStructTypeCache.IsTrackableStructType(type)) { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(type)) { int fieldSlot = GetOrCreateSlot(field, slot); if (fieldSlot > 0 && !State.IsAssigned(fieldSlot)) { RecordReadInLocalFunction(fieldSlot); } } } else { usages.ReadVars[slot] = true; } } private BitVector GetCapturedBitmask() { int n = variableBySlot.Count; BitVector mask = BitVector.AllSet(n); for (int slot = 1; slot < n; slot++) { mask[slot] = IsCapturedInLocalFunction(slot); } return mask; } private bool IsCapturedInLocalFunction(int slot) { if (slot <= 0) return false; // Find the root slot, since that would be the only // slot, if any, that is captured in a local function var rootVarInfo = variableBySlot[RootSlot(slot)]; var rootSymbol = rootVarInfo.Symbol; // A variable is captured in a local function iff its // container is higher in the tree than the nearest // local function var nearestLocalFunc = GetNearestLocalFunctionOpt(CurrentSymbol); return !(nearestLocalFunc is null) && Symbol.IsCaptured(rootSymbol, nearestLocalFunc); } private static LocalFunctionSymbol GetNearestLocalFunctionOpt(Symbol symbol) { while (symbol != null) { if (symbol.Kind == SymbolKind.Method && ((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { return (LocalFunctionSymbol)symbol; } symbol = symbol.ContainingSymbol; } return null; } protected override LocalFunctionState LocalFunctionStart(LocalFunctionState startState) { // Captured variables are definitely assigned if they are assigned on // all branches into the local function, so we store all reads from // possibly unassigned captured variables and later report definite // assignment errors if any of the captured variables is not assigned // on a particular branch. var savedState = CreateLocalFunctionState(); savedState.ReadVars = startState.ReadVars.Clone(); startState.ReadVars.Clear(); return savedState; } /// <summary> /// State changes are handled by the base class. We override to find captured variables that /// have been read before they were assigned and determine if the set has changed. /// </summary> protected override bool LocalFunctionEnd( LocalFunctionState savedState, LocalFunctionState currentState, ref LocalState stateAtReturn) { if (currentState.CapturedMask.IsNull) { currentState.CapturedMask = GetCapturedBitmask(); currentState.InvertedCapturedMask = currentState.CapturedMask.Clone(); currentState.InvertedCapturedMask.Invert(); } // Filter the modified state variables to only captured variables stateAtReturn.Assigned.IntersectWith(currentState.CapturedMask); if (NonMonotonicState.HasValue) { var state = NonMonotonicState.Value; state.Assigned.UnionWith(currentState.InvertedCapturedMask); NonMonotonicState = state; } // Build a list of variables that are both captured and read before assignment var capturedAndRead = currentState.ReadVars; capturedAndRead.IntersectWith(currentState.CapturedMask); // Union and check to see if there are any changes return savedState.ReadVars.UnionWith(capturedAndRead); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp { internal partial class DefiniteAssignmentPass { internal sealed class LocalFunctionState : AbstractLocalFunctionState { public BitVector ReadVars = BitVector.Empty; public BitVector CapturedMask = BitVector.Null; public BitVector InvertedCapturedMask = BitVector.Null; public LocalFunctionState(LocalState stateFromBottom, LocalState stateFromTop) : base(stateFromBottom, stateFromTop) { } } protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol) => CreateLocalFunctionState(); private LocalFunctionState CreateLocalFunctionState() => new LocalFunctionState( // The bottom state should assume all variables, even new ones, are assigned new LocalState(BitVector.AllSet(variableBySlot.Count), normalizeToBottom: true), UnreachableState()); protected override void VisitLocalFunctionUse( LocalFunctionSymbol localFunc, LocalFunctionState localFunctionState, SyntaxNode syntax, bool isCall) { _usedLocalFunctions.Add(localFunc); // Check variables that were read before being definitely assigned. var reads = localFunctionState.ReadVars; // Start at slot 1 (slot 0 just indicates reachability) for (int slot = 1; slot < reads.Capacity; slot++) { if (reads[slot]) { var symbol = variableBySlot[slot].Symbol; CheckIfAssignedDuringLocalFunctionReplay(symbol, syntax, slot); } } base.VisitLocalFunctionUse(localFunc, localFunctionState, syntax, isCall); } /// <summary> /// Check that the given variable is definitely assigned when replaying local function /// reads. If not, produce an error. /// </summary> /// <remarks> /// Specifying the slot manually may be necessary if the symbol is a field, /// in which case <see cref="LocalDataFlowPass{TLocalState, TLocalFunctionState}.VariableSlot(Symbol, int)"/> /// will not know which containing slot to look for. /// </remarks> private void CheckIfAssignedDuringLocalFunctionReplay(Symbol symbol, SyntaxNode node, int slot) { Debug.Assert(!IsConditionalState); if ((object)symbol != null) { NoteRead(symbol); if (this.State.Reachable) { if (slot >= this.State.Assigned.Capacity) { Normalize(ref this.State); } if (slot > 0 && !this.State.IsAssigned(slot)) { // Local functions can "call forward" to after a variable has // been declared but before it has been assigned, so we can never // consider the declaration location when reporting errors. ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, slot, skipIfUseBeforeDeclaration: false); } } } } private void RecordReadInLocalFunction(int slot) { var localFunc = GetNearestLocalFunctionOpt(CurrentSymbol); Debug.Assert(localFunc != null); var usages = GetOrCreateLocalFuncUsages(localFunc); // If this slot is a struct with individually assignable // fields we need to record each field assignment separately, // since some fields may be assigned when this read is replayed VariableIdentifier id = variableBySlot[slot]; var type = id.Symbol.GetTypeOrReturnType().Type; Debug.Assert(!_emptyStructTypeCache.IsEmptyStructType(type)); if (EmptyStructTypeCache.IsTrackableStructType(type)) { foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(type)) { int fieldSlot = GetOrCreateSlot(field, slot); if (fieldSlot > 0 && !State.IsAssigned(fieldSlot)) { RecordReadInLocalFunction(fieldSlot); } } } else { usages.ReadVars[slot] = true; } } private BitVector GetCapturedBitmask() { int n = variableBySlot.Count; BitVector mask = BitVector.AllSet(n); for (int slot = 1; slot < n; slot++) { mask[slot] = IsCapturedInLocalFunction(slot); } return mask; } private bool IsCapturedInLocalFunction(int slot) { if (slot <= 0) return false; // Find the root slot, since that would be the only // slot, if any, that is captured in a local function var rootVarInfo = variableBySlot[RootSlot(slot)]; var rootSymbol = rootVarInfo.Symbol; // A variable is captured in a local function iff its // container is higher in the tree than the nearest // local function var nearestLocalFunc = GetNearestLocalFunctionOpt(CurrentSymbol); return !(nearestLocalFunc is null) && Symbol.IsCaptured(rootSymbol, nearestLocalFunc); } private static LocalFunctionSymbol GetNearestLocalFunctionOpt(Symbol symbol) { while (symbol != null) { if (symbol.Kind == SymbolKind.Method && ((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction) { return (LocalFunctionSymbol)symbol; } symbol = symbol.ContainingSymbol; } return null; } protected override LocalFunctionState LocalFunctionStart(LocalFunctionState startState) { // Captured variables are definitely assigned if they are assigned on // all branches into the local function, so we store all reads from // possibly unassigned captured variables and later report definite // assignment errors if any of the captured variables is not assigned // on a particular branch. var savedState = CreateLocalFunctionState(); savedState.ReadVars = startState.ReadVars.Clone(); startState.ReadVars.Clear(); return savedState; } /// <summary> /// State changes are handled by the base class. We override to find captured variables that /// have been read before they were assigned and determine if the set has changed. /// </summary> protected override bool LocalFunctionEnd( LocalFunctionState savedState, LocalFunctionState currentState, ref LocalState stateAtReturn) { if (currentState.CapturedMask.IsNull) { currentState.CapturedMask = GetCapturedBitmask(); currentState.InvertedCapturedMask = currentState.CapturedMask.Clone(); currentState.InvertedCapturedMask.Invert(); } // Filter the modified state variables to only captured variables stateAtReturn.Assigned.IntersectWith(currentState.CapturedMask); if (NonMonotonicState.HasValue) { var state = NonMonotonicState.Value; state.Assigned.UnionWith(currentState.InvertedCapturedMask); NonMonotonicState = state; } // Build a list of variables that are both captured and read before assignment var capturedAndRead = currentState.ReadVars; capturedAndRead.IntersectWith(currentState.CapturedMask); // Union and check to see if there are any changes return savedState.ReadVars.UnionWith(capturedAndRead); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Portable/FlowAnalysis/NullableWalker_Patterns.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullableWalker { /// <summary> /// Learn something about the input from a test of a given expression against a given pattern. The given /// state is updated to note that any slots that are tested against `null` may be null. /// </summary> private void LearnFromAnyNullPatterns( BoundExpression expression, BoundPattern pattern) { int slot = MakeSlot(expression); LearnFromAnyNullPatterns(slot, expression.Type, pattern); } private void VisitPatternForRewriting(BoundPattern pattern) { // Don't let anything under the pattern actually affect current state, // as we're only visiting for nullable information. Debug.Assert(!IsConditionalState); var currentState = State; VisitWithoutDiagnostics(pattern); SetState(currentState); } public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitRecursivePattern(BoundRecursivePattern node) { Visit(node.DeclaredType); VisitAndUnsplitAll(node.Deconstruction); VisitAndUnsplitAll(node.Properties); Visit(node.VariableAccess); return null; } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node) { Visit(node.VariableAccess); Visit(node.DeclaredType); return null; } public override BoundNode VisitDiscardPattern(BoundDiscardPattern node) { return null; } public override BoundNode VisitTypePattern(BoundTypePattern node) { Visit(node.DeclaredType); return null; } public override BoundNode VisitRelationalPattern(BoundRelationalPattern node) { Visit(node.Value); return null; } public override BoundNode VisitNegatedPattern(BoundNegatedPattern node) { Visit(node.Negated); return null; } public override BoundNode VisitBinaryPattern(BoundBinaryPattern node) { Visit(node.Left); Visit(node.Right); return null; } public override BoundNode VisitITuplePattern(BoundITuplePattern node) { VisitAndUnsplitAll(node.Subpatterns); return null; } /// <summary> /// Learn from any constant null patterns appearing in the pattern. /// </summary> /// <param name="inputType">Type type of the input expression (before nullable analysis). /// Used to determine which types can contain null.</param> private void LearnFromAnyNullPatterns( int inputSlot, TypeSymbol inputType, BoundPattern pattern) { if (inputSlot <= 0) return; // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we // can get information for any nodes in the pattern. VisitPatternForRewriting(pattern); switch (pattern) { case BoundConstantPattern cp: bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null; if (isExplicitNullCheck) { // Since we're not branching on this null test here, we just infer the top level // nullability. We'll branch on it later. LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundDeclarationPattern _: case BoundDiscardPattern _: case BoundITuplePattern _: case BoundRelationalPattern _: break; // nothing to learn case BoundTypePattern tp: if (tp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundRecursivePattern rp: { if (rp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } // for positional part: we only learn from tuples (not Deconstruct) if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault) { var elements = inputType.TupleElements; for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++) { BoundSubpattern item = rp.Deconstruction[i]; FieldSymbol element = elements[i]; LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern); } } // for property part if (!rp.Properties.IsDefault) { foreach (BoundPropertySubpattern subpattern in rp.Properties) { if (subpattern.Member is BoundPropertySubpatternMember member) { LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern); } } } } break; case BoundNegatedPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated); break; case BoundBinaryPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Left); LearnFromAnyNullPatterns(inputSlot, inputType, p.Right); break; default: throw ExceptionUtilities.UnexpectedValue(pattern); } int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot) { if (member.Symbol is null) { return -1; } if (member.Receiver is not null) { inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot); } if (inputSlot < 0) { return inputSlot; } return GetOrCreateSlot(member.Symbol, inputSlot); } } protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern); } } } DeclareLocals(node.InnerLocals); foreach (var section in node.SwitchSections) { // locals can be alive across jumps in the switch sections, so we declare them early. DeclareLocals(section.Locals); } // visit switch header Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false); SetState(labelResult.state); PendingBranches.Add(new PendingBranch(label, this.State, label.Label)); } } var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState(); labelStateMap.Free(); return afterSwitchState; } protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) { TakeIncrementalSnapshot(node); SetState(UnreachableState()); foreach (var label in node.SwitchLabels) { TakeIncrementalSnapshot(label); VisitPatternForRewriting(label.Pattern); VisitLabel(label.Label, node); } VisitStatementList(node); } private struct PossiblyConditionalState { public LocalState State; public LocalState StateWhenTrue; public LocalState StateWhenFalse; public bool IsConditionalState; public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse) { StateWhenTrue = stateWhenTrue.Clone(); StateWhenFalse = stateWhenFalse.Clone(); IsConditionalState = true; State = default; } public PossiblyConditionalState(LocalState state) { StateWhenTrue = StateWhenFalse = default; IsConditionalState = false; State = state.Clone(); } public static PossiblyConditionalState Create(NullableWalker nullableWalker) { return nullableWalker.IsConditionalState ? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse) : new PossiblyConditionalState(nullableWalker.State); } public PossiblyConditionalState Clone() { return IsConditionalState ? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse) : new PossiblyConditionalState(State); } } private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag( SyntaxNode node, BoundDecisionDag decisionDag, BoundExpression expression, TypeWithState expressionType, PossiblyConditionalState? stateWhenNotNullOpt) { // We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are // not copying the input to evaluate the patterns. In this way we infer non-nullability of the original // variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy // of analysis based on this choice. var rootTemp = BoundDagTemp.ForOriginalInput(expression); int originalInputSlot = MakeSlot(expression); if (originalInputSlot <= 0) { originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp); } Debug.Assert(originalInputSlot > 0); // If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of // those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance // to evaluate the patterns. In this way we infer non-nullability of the original element's parts. // We do not extend such courtesy to nested tuple literals. var originalInputElementSlots = expression is BoundTupleExpression tuple ? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this) : default; var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance(); originalInputMap.Add(originalInputSlot, expression); var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance(); Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type)); tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type)); var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance(); nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true)); var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance(); foreach (var dagNode in decisionDag.TopologicallySortedNodes) { bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable); Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes (PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable; if (nodeState.IsConditionalState) { SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse); } else { SetState(nodeState.State); } switch (dagNode) { case BoundEvaluationDecisionDagNode p: { var evaluation = p.Evaluation; (int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable; Debug.Assert(inputSlot > 0); switch (evaluation) { case BoundDagDeconstructEvaluation e: { // https://github.com/dotnet/roslyn/issues/34232 // We may need to recompute the Deconstruct method for a deconstruction if // the receiver type has changed (e.g. its nested nullability). var method = e.DeconstructMethod; int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1; for (int i = 0; i < method.ParameterCount - extensionExtra; i++) { var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i); int outputSlot = makeDagTempSlot(parameterType, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, parameterType.Type); } break; } case BoundDagTypeEvaluation e: { var output = new BoundDagTemp(e.Syntax, e.Type, e); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; int outputSlot; switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: outputSlot = inputSlot; break; case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _): outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true); if (outputSlot < 0) goto default; break; default: outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output); break; } Debug.Assert(!IsConditionalState); Unsplit(); State[outputSlot] = NullableFlowState.NotNull; addToTempMap(output, outputSlot, e.Type); break; } case BoundDagFieldEvaluation e: { Debug.Assert(inputSlot > 0); var field = (FieldSymbol)AsMemberOfType(inputType, e.Field); var type = field.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = -1; var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault ? field : null; if (originalTupleElement is not null) { // Re-use the slot of the element/expression if possible outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex]; } if (outputSlot <= 0) { outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true); if (originalTupleElement is not null && outputSlot > 0) { // The expression in the tuple could not be assigned a slot (for example, `a?.b`), // so we had to create a slot for the tuple element instead. // We'll remember that so that we can apply any learnings to the expression. if (!originalInputMap.ContainsKey(outputSlot)) { originalInputMap.Add(outputSlot, ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } else { Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } } } if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } case BoundDagPropertyEvaluation e: { Debug.Assert(inputSlot > 0); var property = (PropertySymbol)AsMemberOfType(inputType, e.Property); var type = property.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true); if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); if (property.GetMethod is not null) { // A property evaluation splits the state if MemberNotNullWhen is used ApplyMemberPostConditions(inputSlot, property.GetMethod); } break; } case BoundDagIndexEvaluation e: { var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated); var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = makeDagTempSlot(type, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } default: throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind); } gotoNodeWithCurrentState(p.Next, nodeBelievedReachable); break; } case BoundTestDecisionDagNode p: { var test = p.Test; bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType); Debug.Assert(foundTemp); (int inputSlot, TypeSymbol inputType) = slotAndType; Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState); Split(); switch (test) { case BoundDagTypeTest: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagNonNullTest t: var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull(); if (inputSlot > 0) { MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse); if (t.IsExplicitTest) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false); } learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull); break; case BoundDagExplicitNullTest _: if (inputSlot > 0) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true); learnFromNonNullTest(inputSlot, ref this.StateWhenFalse); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagValueTest t: Debug.Assert(t.Value != ConstantValue.Null); // When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following: // [0]: t0 != null ? [1] : [5] // [1]: t1 = (bool)t0; [2] // [2] (this node): t1 == boolConstant ? [3] : [4] // ...(remaining states) if (stateWhenNotNullOpt is { } stateWhenNotNull && t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } }) { SetPossiblyConditionalState(stateWhenNotNull); Split(); } else if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } bool isFalseTest = t.Value == ConstantValue.False; gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagRelationalTest _: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; default: throw ExceptionUtilities.UnexpectedValue(test.Kind); } break; } case BoundLeafDecisionDagNode d: // We have one leaf decision dag node per reachable label Unsplit(); // Could be split in pathological cases like `false switch { ... }` labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable)); break; case BoundWhenDecisionDagNode w: // bind the pattern variables, inferring their types as well Unsplit(); foreach (var binding in w.Bindings) { var variableAccess = binding.VariableAccess; var tempSource = binding.TempContainingValue; var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType); if (foundTemp) // in erroneous programs, we might not have seen a temp defined. { var (tempSlot, tempType) = tempSlotAndType; var tempState = this.State[tempSlot]; if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal) { var value = TypeWithState.Create(tempType, tempState); var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType); if (_variables.TryGetType(local, out var existingType)) { // merge inferred nullable annotation from different branches of the decision tree inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation)); } _variables.SetType(local, inferredType); int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true); if (localSlot > 0) { TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot); } } else { // https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts } } } if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True) { VisitCondition(w.WhenExpression); Debug.Assert(this.IsConditionalState); gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); } else { Debug.Assert(w.WhenFalse is null); gotoNode(w.WhenTrue, this.State, nodeBelievedReachable); } break; default: throw ExceptionUtilities.UnexpectedValue(dagNode.Kind); } } SetUnreachable(); // the decision dag is always complete (no fall-through) originalInputMap.Free(); tempMap.Free(); nodeStateMap.Free(); return labelStateMap; void learnFromNonNullTest(int inputSlot, ref LocalState state) { if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot) { state = CloneAndUnsplit(ref stateWhenNotNull); } LearnFromNonNullTest(inputSlot, ref state); if (originalInputMap.TryGetValue(inputSlot, out var expression)) LearnFromNonNullTest(expression, ref state); } void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type) { // We need to track all dag temps, so there should be a slot Debug.Assert(slot > 0); if (tempMap.TryGetValue(output, out var outputSlotAndType)) { // The dag temp has already been allocated on another branch of the dag Debug.Assert(outputSlotAndType.slot == slot); Debug.Assert(isDerivedType(outputSlotAndType.type, type)); } else { Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type))); tempMap.Add(output, (slot, type)); } } bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType) { if (derivedType.IsErrorType() || baseType.IsErrorType()) return true; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch { ConversionKind.Identity => true, ConversionKind.ImplicitReference => true, ConversionKind.Boxing => true, _ => false, }; } void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable) { if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { switch (IsConditionalState, stateAndReachable.state.IsConditionalState) { case (true, true): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (true, false): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.State); Join(ref this.StateWhenFalse, ref stateAndReachable.state.State); break; case (false, true): Debug.Assert(false); Split(); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (false, false): Join(ref this.State, ref stateAndReachable.state.State); break; } believedReachable |= stateAndReachable.believedReachable; } nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable); } void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable) { PossiblyConditionalState result; if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { result = stateAndReachable.state; switch (result.IsConditionalState) { case true: Debug.Assert(false); Join(ref result.StateWhenTrue, ref state); Join(ref result.StateWhenFalse, ref state); break; case false: Join(ref result.State, ref state); break; } believedReachable |= stateAndReachable.believedReachable; } else { result = new PossiblyConditionalState(state); } nodeStateMap[node] = (result, believedReachable); } int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp) { object slotKey = (node, temp); return GetOrCreatePlaceholderSlot(slotKey, type); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { bool inferType = !node.WasTargetTyped; VisitSwitchExpressionCore(node, inferType); return null; } public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) { // This method is only involved in method inference with unbound lambdas. VisitSwitchExpressionCore(node, inferType: true); return null; } private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var arm in node.SwitchArms) { LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern); } } Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); var endState = UnreachableState(); if (!node.ReportedNotExhaustive && node.DefaultLabel != null && labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable) { SetState(defaultLabelState.state); var nodes = node.DecisionDag.TopologicallySortedNodes; var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First(); var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull; ReportDiagnostic( warningCode, ((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(), samplePattern); } // collect expressions, conversions and result types int numSwitchArms = node.SwitchArms.Length; var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms); var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); foreach (var arm in node.SwitchArms) { SetState(getStateForArm(arm)); // https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot? TakeIncrementalSnapshot(arm); VisitPatternForRewriting(arm.Pattern); (BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(arm.Value, expression); expressions.Add(expression); conversions.Add(conversion); var armType = VisitRvalueWithState(expression); resultTypes.Add(armType); Join(ref endState, ref this.State); // Build placeholders for inference in order to preserve annotations. placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeSymbol inferredType = (inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null) ?? node.Type?.SetUnknownNullabilityForReferenceTypes(); var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType); NullableFlowState inferredState; if (inferType) { if (inferredType is null) { // This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case). // For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and // there is nothing that is being publicly exposed to the semantic model. Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null) || node is BoundSwitchExpression { SwitchArms: { Length: 0 } }); inferredState = default; } else { for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var arm = node.SwitchArms[i]; var armState = getStateForArm(arm); resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable); } inferredState = BestTypeInferrer.GetNullableState(resultTypes); } } else { var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms); for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var armState = getStateForArm(node.SwitchArms[i]); states.Add((armState, resultTypes[i], armState.Reachable)); } ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree()); inferredState = BestTypeInferrer.GetNullableState(resultTypes); } var resultType = TypeWithState.Create(inferredType, inferredState); conversions.Free(); resultTypes.Free(); expressions.Free(); labelStateMap.Free(); SetState(endState); SetResult(node, resultType, inferredTypeWithAnnotations); LocalState getStateForArm(BoundSwitchExpressionArm arm) => !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState(); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); LearnFromAnyNullPatterns(node.Expression, node.Pattern); VisitPatternForRewriting(node.Pattern); var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null); var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState(); var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState(); labelStateMap.Free(); SetConditionalState(trueState, falseState); SetNotNullResult(node); 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. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullableWalker { /// <summary> /// Learn something about the input from a test of a given expression against a given pattern. The given /// state is updated to note that any slots that are tested against `null` may be null. /// </summary> private void LearnFromAnyNullPatterns( BoundExpression expression, BoundPattern pattern) { int slot = MakeSlot(expression); LearnFromAnyNullPatterns(slot, expression.Type, pattern); } private void VisitPatternForRewriting(BoundPattern pattern) { // Don't let anything under the pattern actually affect current state, // as we're only visiting for nullable information. Debug.Assert(!IsConditionalState); var currentState = State; VisitWithoutDiagnostics(pattern); SetState(currentState); } public override BoundNode VisitPositionalSubpattern(BoundPositionalSubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitPropertySubpattern(BoundPropertySubpattern node) { Visit(node.Pattern); return null; } public override BoundNode VisitRecursivePattern(BoundRecursivePattern node) { Visit(node.DeclaredType); VisitAndUnsplitAll(node.Deconstruction); VisitAndUnsplitAll(node.Properties); Visit(node.VariableAccess); return null; } public override BoundNode VisitConstantPattern(BoundConstantPattern node) { VisitRvalue(node.Value); return null; } public override BoundNode VisitDeclarationPattern(BoundDeclarationPattern node) { Visit(node.VariableAccess); Visit(node.DeclaredType); return null; } public override BoundNode VisitDiscardPattern(BoundDiscardPattern node) { return null; } public override BoundNode VisitTypePattern(BoundTypePattern node) { Visit(node.DeclaredType); return null; } public override BoundNode VisitRelationalPattern(BoundRelationalPattern node) { Visit(node.Value); return null; } public override BoundNode VisitNegatedPattern(BoundNegatedPattern node) { Visit(node.Negated); return null; } public override BoundNode VisitBinaryPattern(BoundBinaryPattern node) { Visit(node.Left); Visit(node.Right); return null; } public override BoundNode VisitITuplePattern(BoundITuplePattern node) { VisitAndUnsplitAll(node.Subpatterns); return null; } /// <summary> /// Learn from any constant null patterns appearing in the pattern. /// </summary> /// <param name="inputType">Type type of the input expression (before nullable analysis). /// Used to determine which types can contain null.</param> private void LearnFromAnyNullPatterns( int inputSlot, TypeSymbol inputType, BoundPattern pattern) { if (inputSlot <= 0) return; // https://github.com/dotnet/roslyn/issues/35041 We only need to do this when we're rewriting, so we // can get information for any nodes in the pattern. VisitPatternForRewriting(pattern); switch (pattern) { case BoundConstantPattern cp: bool isExplicitNullCheck = cp.Value.ConstantValue == ConstantValue.Null; if (isExplicitNullCheck) { // Since we're not branching on this null test here, we just infer the top level // nullability. We'll branch on it later. LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundDeclarationPattern _: case BoundDiscardPattern _: case BoundITuplePattern _: case BoundRelationalPattern _: break; // nothing to learn case BoundTypePattern tp: if (tp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } break; case BoundRecursivePattern rp: { if (rp.IsExplicitNotNullTest) { LearnFromNullTest(inputSlot, inputType, ref this.State, markDependentSlotsNotNull: false); } // for positional part: we only learn from tuples (not Deconstruct) if (rp.DeconstructMethod is null && !rp.Deconstruction.IsDefault) { var elements = inputType.TupleElements; for (int i = 0, n = Math.Min(rp.Deconstruction.Length, elements.IsDefault ? 0 : elements.Length); i < n; i++) { BoundSubpattern item = rp.Deconstruction[i]; FieldSymbol element = elements[i]; LearnFromAnyNullPatterns(GetOrCreateSlot(element, inputSlot), element.Type, item.Pattern); } } // for property part if (!rp.Properties.IsDefault) { foreach (BoundPropertySubpattern subpattern in rp.Properties) { if (subpattern.Member is BoundPropertySubpatternMember member) { LearnFromAnyNullPatterns(getExtendedPropertySlot(member, inputSlot), member.Type, subpattern.Pattern); } } } } break; case BoundNegatedPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Negated); break; case BoundBinaryPattern p: LearnFromAnyNullPatterns(inputSlot, inputType, p.Left); LearnFromAnyNullPatterns(inputSlot, inputType, p.Right); break; default: throw ExceptionUtilities.UnexpectedValue(pattern); } int getExtendedPropertySlot(BoundPropertySubpatternMember member, int inputSlot) { if (member.Symbol is null) { return -1; } if (member.Receiver is not null) { inputSlot = getExtendedPropertySlot(member.Receiver, inputSlot); } if (inputSlot < 0) { return inputSlot; } return GetOrCreateSlot(member.Symbol, inputSlot); } } protected override LocalState VisitSwitchStatementDispatch(BoundSwitchStatement node) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { LearnFromAnyNullPatterns(slot, originalInputType, label.Pattern); } } } DeclareLocals(node.InnerLocals); foreach (var section in node.SwitchSections) { // locals can be alive across jumps in the switch sections, so we declare them early. DeclareLocals(section.Locals); } // visit switch header Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); foreach (var section in node.SwitchSections) { foreach (var label in section.SwitchLabels) { var labelResult = labelStateMap.TryGetValue(label.Label, out var s1) ? s1 : (state: UnreachableState(), believedReachable: false); SetState(labelResult.state); PendingBranches.Add(new PendingBranch(label, this.State, label.Label)); } } var afterSwitchState = labelStateMap.TryGetValue(node.BreakLabel, out var stateAndReachable) ? stateAndReachable.state : UnreachableState(); labelStateMap.Free(); return afterSwitchState; } protected override void VisitSwitchSection(BoundSwitchSection node, bool isLastSection) { TakeIncrementalSnapshot(node); SetState(UnreachableState()); foreach (var label in node.SwitchLabels) { TakeIncrementalSnapshot(label); VisitPatternForRewriting(label.Pattern); VisitLabel(label.Label, node); } VisitStatementList(node); } private struct PossiblyConditionalState { public LocalState State; public LocalState StateWhenTrue; public LocalState StateWhenFalse; public bool IsConditionalState; public PossiblyConditionalState(LocalState stateWhenTrue, LocalState stateWhenFalse) { StateWhenTrue = stateWhenTrue.Clone(); StateWhenFalse = stateWhenFalse.Clone(); IsConditionalState = true; State = default; } public PossiblyConditionalState(LocalState state) { StateWhenTrue = StateWhenFalse = default; IsConditionalState = false; State = state.Clone(); } public static PossiblyConditionalState Create(NullableWalker nullableWalker) { return nullableWalker.IsConditionalState ? new PossiblyConditionalState(nullableWalker.StateWhenTrue, nullableWalker.StateWhenFalse) : new PossiblyConditionalState(nullableWalker.State); } public PossiblyConditionalState Clone() { return IsConditionalState ? new PossiblyConditionalState(StateWhenTrue, StateWhenFalse) : new PossiblyConditionalState(State); } } private PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)> LearnFromDecisionDag( SyntaxNode node, BoundDecisionDag decisionDag, BoundExpression expression, TypeWithState expressionType, PossiblyConditionalState? stateWhenNotNullOpt) { // We reuse the slot at the beginning of a switch (or is-pattern expression), pretending that we are // not copying the input to evaluate the patterns. In this way we infer non-nullability of the original // variable's parts based on matched pattern parts. Mutations in `when` clauses can show the inaccuracy // of analysis based on this choice. var rootTemp = BoundDagTemp.ForOriginalInput(expression); int originalInputSlot = MakeSlot(expression); if (originalInputSlot <= 0) { originalInputSlot = makeDagTempSlot(expressionType.ToTypeWithAnnotations(compilation), rootTemp); } Debug.Assert(originalInputSlot > 0); // If the input of the switch (or is-pattern expression) is a tuple literal, we reuse the slots of // those expressions (when possible), pretending that we are not copying them into a temporary ValueTuple instance // to evaluate the patterns. In this way we infer non-nullability of the original element's parts. // We do not extend such courtesy to nested tuple literals. var originalInputElementSlots = expression is BoundTupleExpression tuple ? tuple.Arguments.SelectAsArray(static (a, w) => w.MakeSlot(a), this) : default; var originalInputMap = PooledDictionary<int, BoundExpression>.GetInstance(); originalInputMap.Add(originalInputSlot, expression); var tempMap = PooledDictionary<BoundDagTemp, (int slot, TypeSymbol type)>.GetInstance(); Debug.Assert(isDerivedType(NominalSlotType(originalInputSlot), expressionType.Type)); tempMap.Add(rootTemp, (originalInputSlot, expressionType.Type)); var nodeStateMap = PooledDictionary<BoundDecisionDagNode, (PossiblyConditionalState state, bool believedReachable)>.GetInstance(); nodeStateMap.Add(decisionDag.RootNode, (state: PossiblyConditionalState.Create(this), believedReachable: true)); var labelStateMap = PooledDictionary<LabelSymbol, (LocalState state, bool believedReachable)>.GetInstance(); foreach (var dagNode in decisionDag.TopologicallySortedNodes) { bool found = nodeStateMap.TryGetValue(dagNode, out var nodeStateAndBelievedReachable); Debug.Assert(found); // the topologically sorted nodes should contain only reachable nodes (PossiblyConditionalState nodeState, bool nodeBelievedReachable) = nodeStateAndBelievedReachable; if (nodeState.IsConditionalState) { SetConditionalState(nodeState.StateWhenTrue, nodeState.StateWhenFalse); } else { SetState(nodeState.State); } switch (dagNode) { case BoundEvaluationDecisionDagNode p: { var evaluation = p.Evaluation; (int inputSlot, TypeSymbol inputType) = tempMap.TryGetValue(evaluation.Input, out var slotAndType) ? slotAndType : throw ExceptionUtilities.Unreachable; Debug.Assert(inputSlot > 0); switch (evaluation) { case BoundDagDeconstructEvaluation e: { // https://github.com/dotnet/roslyn/issues/34232 // We may need to recompute the Deconstruct method for a deconstruction if // the receiver type has changed (e.g. its nested nullability). var method = e.DeconstructMethod; int extensionExtra = method.RequiresInstanceReceiver ? 0 : 1; for (int i = 0; i < method.ParameterCount - extensionExtra; i++) { var parameterType = method.Parameters[i + extensionExtra].TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, parameterType.Type, e, i); int outputSlot = makeDagTempSlot(parameterType, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, parameterType.Type); } break; } case BoundDagTypeEvaluation e: { var output = new BoundDagTemp(e.Syntax, e.Type, e); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; int outputSlot; switch (_conversions.WithNullability(false).ClassifyConversionFromType(inputType, e.Type, ref discardedUseSiteInfo).Kind) { case ConversionKind.Identity: case ConversionKind.ImplicitReference: outputSlot = inputSlot; break; case ConversionKind.ExplicitNullable when AreNullableAndUnderlyingTypes(inputType, e.Type, out _): outputSlot = GetNullableOfTValueSlot(inputType, inputSlot, out _, forceSlotEvenIfEmpty: true); if (outputSlot < 0) goto default; break; default: outputSlot = makeDagTempSlot(TypeWithAnnotations.Create(e.Type, NullableAnnotation.NotAnnotated), output); break; } Debug.Assert(!IsConditionalState); Unsplit(); State[outputSlot] = NullableFlowState.NotNull; addToTempMap(output, outputSlot, e.Type); break; } case BoundDagFieldEvaluation e: { Debug.Assert(inputSlot > 0); var field = (FieldSymbol)AsMemberOfType(inputType, e.Field); var type = field.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = -1; var originalTupleElement = e.Input.IsOriginalInput && !originalInputElementSlots.IsDefault ? field : null; if (originalTupleElement is not null) { // Re-use the slot of the element/expression if possible outputSlot = originalInputElementSlots[originalTupleElement.TupleElementIndex]; } if (outputSlot <= 0) { outputSlot = GetOrCreateSlot(field, inputSlot, forceSlotEvenIfEmpty: true); if (originalTupleElement is not null && outputSlot > 0) { // The expression in the tuple could not be assigned a slot (for example, `a?.b`), // so we had to create a slot for the tuple element instead. // We'll remember that so that we can apply any learnings to the expression. if (!originalInputMap.ContainsKey(outputSlot)) { originalInputMap.Add(outputSlot, ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } else { Debug.Assert(originalInputMap[outputSlot] == ((BoundTupleExpression)expression).Arguments[originalTupleElement.TupleElementIndex]); } } } if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } case BoundDagPropertyEvaluation e: { Debug.Assert(inputSlot > 0); var property = (PropertySymbol)AsMemberOfType(inputType, e.Property); var type = property.TypeWithAnnotations; var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = GetOrCreateSlot(property, inputSlot, forceSlotEvenIfEmpty: true); if (outputSlot <= 0) { outputSlot = makeDagTempSlot(type, output); } Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); if (property.GetMethod is not null) { // A property evaluation splits the state if MemberNotNullWhen is used ApplyMemberPostConditions(inputSlot, property.GetMethod); } break; } case BoundDagIndexEvaluation e: { var type = TypeWithAnnotations.Create(e.Property.Type, NullableAnnotation.Annotated); var output = new BoundDagTemp(e.Syntax, type.Type, e); int outputSlot = makeDagTempSlot(type, output); Debug.Assert(outputSlot > 0); addToTempMap(output, outputSlot, type.Type); break; } default: throw ExceptionUtilities.UnexpectedValue(p.Evaluation.Kind); } gotoNodeWithCurrentState(p.Next, nodeBelievedReachable); break; } case BoundTestDecisionDagNode p: { var test = p.Test; bool foundTemp = tempMap.TryGetValue(test.Input, out var slotAndType); Debug.Assert(foundTemp); (int inputSlot, TypeSymbol inputType) = slotAndType; Debug.Assert(test is not BoundDagNonNullTest || !IsConditionalState); Split(); switch (test) { case BoundDagTypeTest: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagNonNullTest t: var inputMaybeNull = this.StateWhenTrue[inputSlot].MayBeNull(); if (inputSlot > 0) { MarkDependentSlotsNotNull(inputSlot, inputType, ref this.StateWhenFalse); if (t.IsExplicitTest) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenFalse, markDependentSlotsNotNull: false); } learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable & inputMaybeNull); break; case BoundDagExplicitNullTest _: if (inputSlot > 0) { LearnFromNullTest(inputSlot, inputType, ref this.StateWhenTrue, markDependentSlotsNotNull: true); learnFromNonNullTest(inputSlot, ref this.StateWhenFalse); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagValueTest t: Debug.Assert(t.Value != ConstantValue.Null); // When we compare `bool?` inputs to bool constants, we follow a graph roughly like the following: // [0]: t0 != null ? [1] : [5] // [1]: t1 = (bool)t0; [2] // [2] (this node): t1 == boolConstant ? [3] : [4] // ...(remaining states) if (stateWhenNotNullOpt is { } stateWhenNotNull && t.Input.Source is BoundDagTypeEvaluation { Input: { IsOriginalInput: true } }) { SetPossiblyConditionalState(stateWhenNotNull); Split(); } else if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } bool isFalseTest = t.Value == ConstantValue.False; gotoNode(p.WhenTrue, isFalseTest ? this.StateWhenFalse : this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, isFalseTest ? this.StateWhenTrue : this.StateWhenFalse, nodeBelievedReachable); break; case BoundDagRelationalTest _: if (inputSlot > 0) { learnFromNonNullTest(inputSlot, ref this.StateWhenTrue); } gotoNode(p.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(p.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); break; default: throw ExceptionUtilities.UnexpectedValue(test.Kind); } break; } case BoundLeafDecisionDagNode d: // We have one leaf decision dag node per reachable label Unsplit(); // Could be split in pathological cases like `false switch { ... }` labelStateMap.Add(d.Label, (this.State, nodeBelievedReachable)); break; case BoundWhenDecisionDagNode w: // bind the pattern variables, inferring their types as well Unsplit(); foreach (var binding in w.Bindings) { var variableAccess = binding.VariableAccess; var tempSource = binding.TempContainingValue; var foundTemp = tempMap.TryGetValue(tempSource, out var tempSlotAndType); if (foundTemp) // in erroneous programs, we might not have seen a temp defined. { var (tempSlot, tempType) = tempSlotAndType; var tempState = this.State[tempSlot]; if (variableAccess is BoundLocal { LocalSymbol: SourceLocalSymbol local } boundLocal) { var value = TypeWithState.Create(tempType, tempState); var inferredType = value.ToTypeWithAnnotations(compilation, asAnnotatedType: boundLocal.DeclarationKind == BoundLocalDeclarationKind.WithInferredType); if (_variables.TryGetType(local, out var existingType)) { // merge inferred nullable annotation from different branches of the decision tree inferredType = TypeWithAnnotations.Create(inferredType.Type, existingType.NullableAnnotation.Join(inferredType.NullableAnnotation)); } _variables.SetType(local, inferredType); int localSlot = GetOrCreateSlot(local, forceSlotEvenIfEmpty: true); if (localSlot > 0) { TrackNullableStateForAssignment(valueOpt: null, inferredType, localSlot, TypeWithState.Create(tempType, tempState), tempSlot); } } else { // https://github.com/dotnet/roslyn/issues/34144 perform inference for top-level var-declared fields in scripts } } } if (w.WhenExpression != null && w.WhenExpression.ConstantValue != ConstantValue.True) { VisitCondition(w.WhenExpression); Debug.Assert(this.IsConditionalState); gotoNode(w.WhenTrue, this.StateWhenTrue, nodeBelievedReachable); gotoNode(w.WhenFalse, this.StateWhenFalse, nodeBelievedReachable); } else { Debug.Assert(w.WhenFalse is null); gotoNode(w.WhenTrue, this.State, nodeBelievedReachable); } break; default: throw ExceptionUtilities.UnexpectedValue(dagNode.Kind); } } SetUnreachable(); // the decision dag is always complete (no fall-through) originalInputMap.Free(); tempMap.Free(); nodeStateMap.Free(); return labelStateMap; void learnFromNonNullTest(int inputSlot, ref LocalState state) { if (stateWhenNotNullOpt is { } stateWhenNotNull && inputSlot == originalInputSlot) { state = CloneAndUnsplit(ref stateWhenNotNull); } LearnFromNonNullTest(inputSlot, ref state); if (originalInputMap.TryGetValue(inputSlot, out var expression)) LearnFromNonNullTest(expression, ref state); } void addToTempMap(BoundDagTemp output, int slot, TypeSymbol type) { // We need to track all dag temps, so there should be a slot Debug.Assert(slot > 0); if (tempMap.TryGetValue(output, out var outputSlotAndType)) { // The dag temp has already been allocated on another branch of the dag Debug.Assert(outputSlotAndType.slot == slot); Debug.Assert(isDerivedType(outputSlotAndType.type, type)); } else { Debug.Assert(NominalSlotType(slot) is var slotType && (slotType.IsErrorType() || isDerivedType(slotType, type))); tempMap.Add(output, (slot, type)); } } bool isDerivedType(TypeSymbol derivedType, TypeSymbol baseType) { if (derivedType.IsErrorType() || baseType.IsErrorType()) return true; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return _conversions.WithNullability(false).ClassifyConversionFromType(derivedType, baseType, ref discardedUseSiteInfo).Kind switch { ConversionKind.Identity => true, ConversionKind.ImplicitReference => true, ConversionKind.Boxing => true, _ => false, }; } void gotoNodeWithCurrentState(BoundDecisionDagNode node, bool believedReachable) { if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { switch (IsConditionalState, stateAndReachable.state.IsConditionalState) { case (true, true): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (true, false): Debug.Assert(false); Join(ref this.StateWhenTrue, ref stateAndReachable.state.State); Join(ref this.StateWhenFalse, ref stateAndReachable.state.State); break; case (false, true): Debug.Assert(false); Split(); Join(ref this.StateWhenTrue, ref stateAndReachable.state.StateWhenTrue); Join(ref this.StateWhenFalse, ref stateAndReachable.state.StateWhenFalse); break; case (false, false): Join(ref this.State, ref stateAndReachable.state.State); break; } believedReachable |= stateAndReachable.believedReachable; } nodeStateMap[node] = (PossiblyConditionalState.Create(this), believedReachable); } void gotoNode(BoundDecisionDagNode node, LocalState state, bool believedReachable) { PossiblyConditionalState result; if (nodeStateMap.TryGetValue(node, out var stateAndReachable)) { result = stateAndReachable.state; switch (result.IsConditionalState) { case true: Debug.Assert(false); Join(ref result.StateWhenTrue, ref state); Join(ref result.StateWhenFalse, ref state); break; case false: Join(ref result.State, ref state); break; } believedReachable |= stateAndReachable.believedReachable; } else { result = new PossiblyConditionalState(state); } nodeStateMap[node] = (result, believedReachable); } int makeDagTempSlot(TypeWithAnnotations type, BoundDagTemp temp) { object slotKey = (node, temp); return GetOrCreatePlaceholderSlot(slotKey, type); } } public override BoundNode VisitConvertedSwitchExpression(BoundConvertedSwitchExpression node) { bool inferType = !node.WasTargetTyped; VisitSwitchExpressionCore(node, inferType); return null; } public override BoundNode VisitUnconvertedSwitchExpression(BoundUnconvertedSwitchExpression node) { // This method is only involved in method inference with unbound lambdas. VisitSwitchExpressionCore(node, inferType: true); return null; } private void VisitSwitchExpressionCore(BoundSwitchExpression node, bool inferType) { // first, learn from any null tests in the patterns int slot = node.Expression.IsSuppressed ? GetOrCreatePlaceholderSlot(node.Expression) : MakeSlot(node.Expression); if (slot > 0) { var originalInputType = node.Expression.Type; foreach (var arm in node.SwitchArms) { LearnFromAnyNullPatterns(slot, originalInputType, arm.Pattern); } } Visit(node.Expression); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, stateWhenNotNullOpt: null); var endState = UnreachableState(); if (!node.ReportedNotExhaustive && node.DefaultLabel != null && labelStateMap.TryGetValue(node.DefaultLabel, out var defaultLabelState) && defaultLabelState.believedReachable) { SetState(defaultLabelState.state); var nodes = node.DecisionDag.TopologicallySortedNodes; var leaf = nodes.Where(n => n is BoundLeafDecisionDagNode leaf && leaf.Label == node.DefaultLabel).First(); var samplePattern = PatternExplainer.SamplePatternForPathToDagNode( BoundDagTemp.ForOriginalInput(node.Expression), nodes, leaf, nullPaths: true, out bool requiresFalseWhenClause, out _); ErrorCode warningCode = requiresFalseWhenClause ? ErrorCode.WRN_SwitchExpressionNotExhaustiveForNullWithWhen : ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull; ReportDiagnostic( warningCode, ((SwitchExpressionSyntax)node.Syntax).SwitchKeyword.GetLocation(), samplePattern); } // collect expressions, conversions and result types int numSwitchArms = node.SwitchArms.Length; var conversions = ArrayBuilder<Conversion>.GetInstance(numSwitchArms); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(numSwitchArms); var expressions = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); var placeholderBuilder = ArrayBuilder<BoundExpression>.GetInstance(numSwitchArms); foreach (var arm in node.SwitchArms) { SetState(getStateForArm(arm)); // https://github.com/dotnet/roslyn/issues/35836 Is this where we want to take the snapshot? TakeIncrementalSnapshot(arm); VisitPatternForRewriting(arm.Pattern); (BoundExpression expression, Conversion conversion) = RemoveConversion(arm.Value, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(arm.Value, expression); expressions.Add(expression); conversions.Add(conversion); var armType = VisitRvalueWithState(expression); resultTypes.Add(armType); Join(ref endState, ref this.State); // Build placeholders for inference in order to preserve annotations. placeholderBuilder.Add(CreatePlaceholderIfNecessary(expression, armType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeSymbol inferredType = (inferType ? BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo) : null) ?? node.Type?.SetUnknownNullabilityForReferenceTypes(); var inferredTypeWithAnnotations = TypeWithAnnotations.Create(inferredType); NullableFlowState inferredState; if (inferType) { if (inferredType is null) { // This can happen when we're inferring the return type of a lambda, or when there are no arms (an error case). // For this case, we don't need to do any work, as the unconverted switch expression can't contribute info, and // there is nothing that is being publicly exposed to the semantic model. Debug.Assert((node is BoundUnconvertedSwitchExpression && _returnTypesOpt is not null) || node is BoundSwitchExpression { SwitchArms: { Length: 0 } }); inferredState = default; } else { for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var arm = node.SwitchArms[i]; var armState = getStateForArm(arm); resultTypes[i] = ConvertConditionalOperandOrSwitchExpressionArmResult(arm.Value, nodeForSyntax, conversions[i], inferredTypeWithAnnotations, resultTypes[i], armState, armState.Reachable); } inferredState = BestTypeInferrer.GetNullableState(resultTypes); } } else { var states = ArrayBuilder<(LocalState, TypeWithState, bool)>.GetInstance(numSwitchArms); for (int i = 0; i < numSwitchArms; i++) { var nodeForSyntax = expressions[i]; var armState = getStateForArm(node.SwitchArms[i]); states.Add((armState, resultTypes[i], armState.Reachable)); } ConditionalInfoForConversion.Add(node, states.ToImmutableAndFree()); inferredState = BestTypeInferrer.GetNullableState(resultTypes); } var resultType = TypeWithState.Create(inferredType, inferredState); conversions.Free(); resultTypes.Free(); expressions.Free(); labelStateMap.Free(); SetState(endState); SetResult(node, resultType, inferredTypeWithAnnotations); LocalState getStateForArm(BoundSwitchExpressionArm arm) => !arm.Pattern.HasErrors && labelStateMap.TryGetValue(arm.Label, out var labelState) ? labelState.state : UnreachableState(); } public override BoundNode VisitIsPatternExpression(BoundIsPatternExpression node) { Debug.Assert(!IsConditionalState); LearnFromAnyNullPatterns(node.Expression, node.Pattern); VisitPatternForRewriting(node.Pattern); var hasStateWhenNotNull = VisitPossibleConditionalAccess(node.Expression, out var conditionalStateWhenNotNull); var expressionState = ResultType; var labelStateMap = LearnFromDecisionDag(node.Syntax, node.DecisionDag, node.Expression, expressionState, hasStateWhenNotNull ? conditionalStateWhenNotNull : null); var trueState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenFalseLabel : node.WhenTrueLabel, out var s1) ? s1.state : UnreachableState(); var falseState = labelStateMap.TryGetValue(node.IsNegated ? node.WhenTrueLabel : node.WhenFalseLabel, out var s2) ? s2.state : UnreachableState(); labelStateMap.Free(); SetConditionalState(trueState, falseState); SetNotNullResult(node); return null; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/Core/Def/Interactive/ScriptingOleCommandTarget.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Interactive { /// <summary> /// This command target routes commands in interactive window, .csx files and also interactive /// commands in .cs files. /// </summary> internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget { internal ScriptingOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) : base(wpfTextView, componentModel) { } protected override ITextBuffer? GetSubjectBufferContainingCaret() { var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType); if (result == null) { result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.VisualStudio.LanguageServices.Interactive { /// <summary> /// This command target routes commands in interactive window, .csx files and also interactive /// commands in .cs files. /// </summary> internal sealed class ScriptingOleCommandTarget : AbstractOleCommandTarget { internal ScriptingOleCommandTarget( IWpfTextView wpfTextView, IComponentModel componentModel) : base(wpfTextView, componentModel) { } protected override ITextBuffer? GetSubjectBufferContainingCaret() { var result = WpfTextView.GetBufferContainingCaret(contentType: ContentTypeNames.RoslynContentType); if (result == null) { result = WpfTextView.GetBufferContainingCaret(contentType: PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); } return result; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/Portable/Diagnostic/SourceLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in source code. /// </summary> internal sealed class SourceLocation : Location, IEquatable<SourceLocation?> { private readonly SyntaxTree _syntaxTree; private readonly TextSpan _span; public SourceLocation(SyntaxTree syntaxTree, TextSpan span) { _syntaxTree = syntaxTree; _span = span; } public SourceLocation(SyntaxNode node) : this(node.SyntaxTree, node.Span) { } public SourceLocation(in SyntaxToken token) : this(token.SyntaxTree!, token.Span) { } public SourceLocation(in SyntaxNodeOrToken nodeOrToken) : this(nodeOrToken.SyntaxTree!, nodeOrToken.Span) { Debug.Assert(nodeOrToken.SyntaxTree is object); } public SourceLocation(in SyntaxTrivia trivia) : this(trivia.SyntaxTree!, trivia.Span) { Debug.Assert(trivia.SyntaxTree is object); } public SourceLocation(SyntaxReference syntaxRef) : this(syntaxRef.SyntaxTree, syntaxRef.Span) { // If we're using a syntaxref, we don't have a node in hand, so we couldn't get equality // on syntax node, so associatedNodeOpt shouldn't be set. We never use this constructor // when binding executable code anywhere, so it has no use. } public override LocationKind Kind { get { return LocationKind.SourceFile; } } public override TextSpan SourceSpan { get { return _span; } } public override SyntaxTree SourceTree { get { return _syntaxTree; } } public override FileLinePositionSpan GetLineSpan() { // If there's no syntax tree (e.g. because we're binding speculatively), // then just return an invalid span. if (_syntaxTree == null) { FileLinePositionSpan result = default(FileLinePositionSpan); Debug.Assert(!result.IsValid); return result; } return _syntaxTree.GetLineSpan(_span); } public override FileLinePositionSpan GetMappedLineSpan() { // If there's no syntax tree (e.g. because we're binding speculatively), // then just return an invalid span. if (_syntaxTree == null) { FileLinePositionSpan result = default(FileLinePositionSpan); Debug.Assert(!result.IsValid); return result; } return _syntaxTree.GetMappedLineSpan(_span); } public bool Equals(SourceLocation? other) { if (ReferenceEquals(this, other)) { return true; } return other != null && other._syntaxTree == _syntaxTree && other._span == _span; } public override bool Equals(object? obj) { return this.Equals(obj as SourceLocation); } public override int GetHashCode() { return Hash.Combine(_syntaxTree, _span.GetHashCode()); } protected override string GetDebuggerDisplay() { return base.GetDebuggerDisplay() + "\"" + _syntaxTree.ToString().Substring(_span.Start, _span.Length) + "\""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in source code. /// </summary> internal sealed class SourceLocation : Location, IEquatable<SourceLocation?> { private readonly SyntaxTree _syntaxTree; private readonly TextSpan _span; public SourceLocation(SyntaxTree syntaxTree, TextSpan span) { _syntaxTree = syntaxTree; _span = span; } public SourceLocation(SyntaxNode node) : this(node.SyntaxTree, node.Span) { } public SourceLocation(in SyntaxToken token) : this(token.SyntaxTree!, token.Span) { } public SourceLocation(in SyntaxNodeOrToken nodeOrToken) : this(nodeOrToken.SyntaxTree!, nodeOrToken.Span) { Debug.Assert(nodeOrToken.SyntaxTree is object); } public SourceLocation(in SyntaxTrivia trivia) : this(trivia.SyntaxTree!, trivia.Span) { Debug.Assert(trivia.SyntaxTree is object); } public SourceLocation(SyntaxReference syntaxRef) : this(syntaxRef.SyntaxTree, syntaxRef.Span) { // If we're using a syntaxref, we don't have a node in hand, so we couldn't get equality // on syntax node, so associatedNodeOpt shouldn't be set. We never use this constructor // when binding executable code anywhere, so it has no use. } public override LocationKind Kind { get { return LocationKind.SourceFile; } } public override TextSpan SourceSpan { get { return _span; } } public override SyntaxTree SourceTree { get { return _syntaxTree; } } public override FileLinePositionSpan GetLineSpan() { // If there's no syntax tree (e.g. because we're binding speculatively), // then just return an invalid span. if (_syntaxTree == null) { FileLinePositionSpan result = default(FileLinePositionSpan); Debug.Assert(!result.IsValid); return result; } return _syntaxTree.GetLineSpan(_span); } public override FileLinePositionSpan GetMappedLineSpan() { // If there's no syntax tree (e.g. because we're binding speculatively), // then just return an invalid span. if (_syntaxTree == null) { FileLinePositionSpan result = default(FileLinePositionSpan); Debug.Assert(!result.IsValid); return result; } return _syntaxTree.GetMappedLineSpan(_span); } public bool Equals(SourceLocation? other) { if (ReferenceEquals(this, other)) { return true; } return other != null && other._syntaxTree == _syntaxTree && other._span == _span; } public override bool Equals(object? obj) { return this.Equals(obj as SourceLocation); } public override int GetHashCode() { return Hash.Combine(_syntaxTree, _span.GetHashCode()); } protected override string GetDebuggerDisplay() { return base.GetDebuggerDisplay() + "\"" + _syntaxTree.ToString().Substring(_span.Start, _span.Length) + "\""; } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/IUnitTestingIncrementalAnalyzerProviderImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExternalAccess.UnitTesting.Api { internal interface IUnitTestingIncrementalAnalyzerProviderImplementation { IUnitTestingIncrementalAnalyzerImplementation CreateIncrementalAnalyzer(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.ExternalAccess.UnitTesting.Api { internal interface IUnitTestingIncrementalAnalyzerProviderImplementation { IUnitTestingIncrementalAnalyzerImplementation CreateIncrementalAnalyzer(); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationStartedEvent.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// The first event placed into a compilation's event queue. /// </summary> internal sealed class CompilationStartedEvent : CompilationEvent { public ImmutableArray<AdditionalText> AdditionalFiles { get; } private CompilationStartedEvent(Compilation compilation, ImmutableArray<AdditionalText> additionalFiles) : base(compilation) { AdditionalFiles = additionalFiles; } public CompilationStartedEvent(Compilation compilation) : this(compilation, ImmutableArray<AdditionalText>.Empty) { } public override string ToString() { return "CompilationStartedEvent"; } public CompilationStartedEvent WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) => new CompilationStartedEvent(Compilation, additionalFiles); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// The first event placed into a compilation's event queue. /// </summary> internal sealed class CompilationStartedEvent : CompilationEvent { public ImmutableArray<AdditionalText> AdditionalFiles { get; } private CompilationStartedEvent(Compilation compilation, ImmutableArray<AdditionalText> additionalFiles) : base(compilation) { AdditionalFiles = additionalFiles; } public CompilationStartedEvent(Compilation compilation) : this(compilation, ImmutableArray<AdditionalText>.Empty) { } public override string ToString() { return "CompilationStartedEvent"; } public CompilationStartedEvent WithAdditionalFiles(ImmutableArray<AdditionalText> additionalFiles) => new CompilationStartedEvent(Compilation, additionalFiles); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/LanguageServer/ProtocolUnitTests/Completion/CompletionResolveTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Newtonsoft.Json; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion { public class CompletionResolveTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestResolveCompletionItemFromListAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCapabilities = new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new TextDocumentClientCapabilities() { Completion = new VSInternalCompletionSetting() { CompletionList = new VSInternalCompletionListSetting() { Data = true, } } } }; var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>( testLspServer, locations, label: "A", clientCapabilities).ConfigureAwait(false); var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A")); var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false); AssertJsonEquals(expected, results); } [Fact] public async Task TestResolveCompletionItemAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "A").ConfigureAwait(false); var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A")); var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); AssertJsonEquals(expected, results); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItemAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "M()").ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); Assert.Equal(@"public override void M() { throw new System.NotImplementedException(); }", results.TextEdit.NewText); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabledAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); // Explicitly enable snippets. This allows us to set the cursor with $0. Currently only applies to C# in Razor docs. var clientCapabilities = new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new LSP.TextDocumentClientCapabilities { Completion = new CompletionSetting { CompletionItem = new CompletionItemSetting { SnippetSupport = true } } } }; var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>( testLspServer, locations, label: "M()", clientCapabilities).ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false); Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); Assert.Equal(@"public override void M() { throw new System.NotImplementedException();$0 }", results.TextEdit.NewText); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabled_CaretOutOfSnippetScopeAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out _); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var selectedItem = CodeAnalysis.Completion.CompletionItem.Create(displayText: "M"); var textEdit = await CompletionResolveHandler.GenerateTextEditAsync( document, new TestCaretOutOfScopeCompletionService(), selectedItem, snippetsSupported: true, CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"public override void M() { throw new System.NotImplementedException(); }", textEdit.NewText); } [Fact] public async Task TestResolveCompletionItemWithMarkupContentAsync() { var markup = @" class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> void AMethod(int i) { } void M() { AMet{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>( testLspServer, locations, label: "AMethod", new ClientCapabilities()).ConfigureAwait(false); Assert.True(clientCompletionItem is not VSInternalCompletionItem); var expected = @"```csharp void A.AMethod(int i) ``` A&nbsp;cref&nbsp;A\.AMethod\(int\) **strong&nbsp;text** _italic&nbsp;text_ <u>underline&nbsp;text</u> •&nbsp;Item&nbsp;1\. •&nbsp;Item&nbsp;2\. [link text](https://google.com)"; var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { Completion = new CompletionSetting { CompletionItem = new CompletionItemSetting { DocumentationFormat = new MarkupKind[] { MarkupKind.Markdown } } } } }).ConfigureAwait(false); Assert.Equal(expected, results.Documentation.Value.Second.Value); } [Fact] public async Task TestResolveCompletionItemWithPlainTextAsync() { var markup = @" class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> void AMethod(int i) { } void M() { AMet{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>( testLspServer, locations, label: "AMethod", new ClientCapabilities()).ConfigureAwait(false); Assert.True(clientCompletionItem is not VSInternalCompletionItem); var expected = @"void A.AMethod(int i) A cref A.AMethod(int) strong text italic text underline text • Item 1. • Item 2. link text"; var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, new ClientCapabilities()).ConfigureAwait(false); Assert.Equal(expected, results.Documentation.Value.Second.Value); } [Fact] public async Task TestResolveCompletionItemWithPrefixSuffixAsync() { var markup = @"class A { void M() { var a = 10; a.{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "(byte)").ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); Assert.Equal("(byte)", results.Label); Assert.NotNull(results.Description); } private static async Task<LSP.CompletionItem> RunResolveCompletionItemAsync(TestLspServer testLspServer, LSP.CompletionItem completionItem, LSP.ClientCapabilities clientCapabilities = null) { clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }; return await testLspServer.ExecuteRequestAsync<LSP.CompletionItem, LSP.CompletionItem>(LSP.Methods.TextDocumentCompletionResolveName, completionItem, clientCapabilities, null, CancellationToken.None); } private static LSP.VSInternalCompletionItem CreateResolvedCompletionItem( VSInternalCompletionItem completionItem, ClassifiedTextElement description, string detail, string documentation) { completionItem.Detail = detail; if (documentation != null) { completionItem.Documentation = new LSP.MarkupContent() { Kind = LSP.MarkupKind.PlainText, Value = documentation }; } completionItem.Description = description; return completionItem; } private static ClassifiedTextRun[] CreateClassifiedTextRunForClass(string className) => new ClassifiedTextRun[] { new ClassifiedTextRun("keyword", "class"), new ClassifiedTextRun("whitespace", " "), new ClassifiedTextRun("class name", className) }; private static async Task<T> GetCompletionItemToResolveAsync<T>( TestLspServer testLspServer, Dictionary<string, IList<LSP.Location>> locations, string label, LSP.ClientCapabilities clientCapabilities = null) where T : LSP.CompletionItem { var completionParams = CreateCompletionParams( locations["caret"].Single(), LSP.VSInternalCompletionInvokeKind.Explicit, "\0", LSP.CompletionTriggerKind.Invoked); clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }; var completionList = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities); if (clientCapabilities.HasCompletionListDataCapability()) { var vsCompletionList = Assert.IsAssignableFrom<VSInternalCompletionList>(completionList); Assert.NotNull(vsCompletionList.Data); } var serverCompletionItem = completionList.Items.FirstOrDefault(item => item.Label == label); var clientCompletionItem = ConvertToClientCompletionItem((T)serverCompletionItem); return clientCompletionItem; } private static async Task<LSP.CompletionList> RunGetCompletionsAsync( TestLspServer testLspServer, LSP.CompletionParams completionParams, LSP.ClientCapabilities clientCapabilities) { var completionList = await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName, completionParams, clientCapabilities, null, CancellationToken.None); // Emulate client behavior of promoting "Data" completion list properties onto completion items. if (clientCapabilities.HasCompletionListDataCapability() && completionList is VSInternalCompletionList vsCompletionList && vsCompletionList.Data != null) { foreach (var completionItem in completionList.Items) { Assert.Null(completionItem.Data); completionItem.Data = vsCompletionList.Data; } } return completionList; } private static T ConvertToClientCompletionItem<T>(T serverCompletionItem) where T : LSP.CompletionItem { var serializedItem = JsonConvert.SerializeObject(serverCompletionItem); var clientCompletionItem = JsonConvert.DeserializeObject<T>(serializedItem); return clientCompletionItem; } private class TestCaretOutOfScopeCompletionService : CompletionService { public override string Language => LanguageNames.CSharp; public override Task<CodeAnalysis.Completion.CompletionList> GetCompletionsAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default) => Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty); public override Task<CompletionChange> GetChangeAsync( Document document, CodeAnalysis.Completion.CompletionItem item, char? commitCharacter = null, CancellationToken cancellationToken = default) { var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: @"public override void M() { throw new System.NotImplementedException(); }"); return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text.Adornments; using Newtonsoft.Json; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Completion { public class CompletionResolveTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestResolveCompletionItemFromListAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCapabilities = new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new TextDocumentClientCapabilities() { Completion = new VSInternalCompletionSetting() { CompletionList = new VSInternalCompletionListSetting() { Data = true, } } } }; var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>( testLspServer, locations, label: "A", clientCapabilities).ConfigureAwait(false); var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A")); var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false); AssertJsonEquals(expected, results); } [Fact] public async Task TestResolveCompletionItemAsync() { var markup = @"class A { void M() { {|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "A").ConfigureAwait(false); var description = new ClassifiedTextElement(CreateClassifiedTextRunForClass("A")); var expected = CreateResolvedCompletionItem(clientCompletionItem, description, "class A", null); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); AssertJsonEquals(expected, results); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItemAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "M()").ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); Assert.Equal(@"public override void M() { throw new System.NotImplementedException(); }", results.TextEdit.NewText); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabledAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); // Explicitly enable snippets. This allows us to set the cursor with $0. Currently only applies to C# in Razor docs. var clientCapabilities = new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true, TextDocument = new LSP.TextDocumentClientCapabilities { Completion = new CompletionSetting { CompletionItem = new CompletionItemSetting { SnippetSupport = true } } } }; var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>( testLspServer, locations, label: "M()", clientCapabilities).ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, clientCapabilities).ConfigureAwait(false); Assert.NotNull(results.TextEdit); Assert.Null(results.InsertText); Assert.Equal(@"public override void M() { throw new System.NotImplementedException();$0 }", results.TextEdit.NewText); } [Fact] [WorkItem(51125, "https://github.com/dotnet/roslyn/issues/51125")] public async Task TestResolveOverridesCompletionItem_SnippetsEnabled_CaretOutOfSnippetScopeAsync() { var markup = @"abstract class A { public abstract void M(); } class B : A { override {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out _); var document = testLspServer.GetCurrentSolution().Projects.First().Documents.First(); var selectedItem = CodeAnalysis.Completion.CompletionItem.Create(displayText: "M"); var textEdit = await CompletionResolveHandler.GenerateTextEditAsync( document, new TestCaretOutOfScopeCompletionService(), selectedItem, snippetsSupported: true, CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"public override void M() { throw new System.NotImplementedException(); }", textEdit.NewText); } [Fact] public async Task TestResolveCompletionItemWithMarkupContentAsync() { var markup = @" class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> void AMethod(int i) { } void M() { AMet{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>( testLspServer, locations, label: "AMethod", new ClientCapabilities()).ConfigureAwait(false); Assert.True(clientCompletionItem is not VSInternalCompletionItem); var expected = @"```csharp void A.AMethod(int i) ``` A&nbsp;cref&nbsp;A\.AMethod\(int\) **strong&nbsp;text** _italic&nbsp;text_ <u>underline&nbsp;text</u> •&nbsp;Item&nbsp;1\. •&nbsp;Item&nbsp;2\. [link text](https://google.com)"; var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, new ClientCapabilities { TextDocument = new TextDocumentClientCapabilities { Completion = new CompletionSetting { CompletionItem = new CompletionItemSetting { DocumentationFormat = new MarkupKind[] { MarkupKind.Markdown } } } } }).ConfigureAwait(false); Assert.Equal(expected, results.Documentation.Value.Second.Value); } [Fact] public async Task TestResolveCompletionItemWithPlainTextAsync() { var markup = @" class A { /// <summary> /// A cref <see cref=""AMethod""/> /// <br/> /// <strong>strong text</strong> /// <br/> /// <em>italic text</em> /// <br/> /// <u>underline text</u> /// <para> /// <list type='bullet'> /// <item> /// <description>Item 1.</description> /// </item> /// <item> /// <description>Item 2.</description> /// </item> /// </list> /// <a href = ""https://google.com"" > link text</a> /// </para> /// </summary> void AMethod(int i) { } void M() { AMet{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.CompletionItem>( testLspServer, locations, label: "AMethod", new ClientCapabilities()).ConfigureAwait(false); Assert.True(clientCompletionItem is not VSInternalCompletionItem); var expected = @"void A.AMethod(int i) A cref A.AMethod(int) strong text italic text underline text • Item 1. • Item 2. link text"; var results = await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem, new ClientCapabilities()).ConfigureAwait(false); Assert.Equal(expected, results.Documentation.Value.Second.Value); } [Fact] public async Task TestResolveCompletionItemWithPrefixSuffixAsync() { var markup = @"class A { void M() { var a = 10; a.{|caret:|} } }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var clientCompletionItem = await GetCompletionItemToResolveAsync<LSP.VSInternalCompletionItem>(testLspServer, locations, label: "(byte)").ConfigureAwait(false); var results = (LSP.VSInternalCompletionItem)await RunResolveCompletionItemAsync( testLspServer, clientCompletionItem).ConfigureAwait(false); Assert.Equal("(byte)", results.Label); Assert.NotNull(results.Description); } private static async Task<LSP.CompletionItem> RunResolveCompletionItemAsync(TestLspServer testLspServer, LSP.CompletionItem completionItem, LSP.ClientCapabilities clientCapabilities = null) { clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }; return await testLspServer.ExecuteRequestAsync<LSP.CompletionItem, LSP.CompletionItem>(LSP.Methods.TextDocumentCompletionResolveName, completionItem, clientCapabilities, null, CancellationToken.None); } private static LSP.VSInternalCompletionItem CreateResolvedCompletionItem( VSInternalCompletionItem completionItem, ClassifiedTextElement description, string detail, string documentation) { completionItem.Detail = detail; if (documentation != null) { completionItem.Documentation = new LSP.MarkupContent() { Kind = LSP.MarkupKind.PlainText, Value = documentation }; } completionItem.Description = description; return completionItem; } private static ClassifiedTextRun[] CreateClassifiedTextRunForClass(string className) => new ClassifiedTextRun[] { new ClassifiedTextRun("keyword", "class"), new ClassifiedTextRun("whitespace", " "), new ClassifiedTextRun("class name", className) }; private static async Task<T> GetCompletionItemToResolveAsync<T>( TestLspServer testLspServer, Dictionary<string, IList<LSP.Location>> locations, string label, LSP.ClientCapabilities clientCapabilities = null) where T : LSP.CompletionItem { var completionParams = CreateCompletionParams( locations["caret"].Single(), LSP.VSInternalCompletionInvokeKind.Explicit, "\0", LSP.CompletionTriggerKind.Invoked); clientCapabilities ??= new LSP.VSInternalClientCapabilities { SupportsVisualStudioExtensions = true }; var completionList = await RunGetCompletionsAsync(testLspServer, completionParams, clientCapabilities); if (clientCapabilities.HasCompletionListDataCapability()) { var vsCompletionList = Assert.IsAssignableFrom<VSInternalCompletionList>(completionList); Assert.NotNull(vsCompletionList.Data); } var serverCompletionItem = completionList.Items.FirstOrDefault(item => item.Label == label); var clientCompletionItem = ConvertToClientCompletionItem((T)serverCompletionItem); return clientCompletionItem; } private static async Task<LSP.CompletionList> RunGetCompletionsAsync( TestLspServer testLspServer, LSP.CompletionParams completionParams, LSP.ClientCapabilities clientCapabilities) { var completionList = await testLspServer.ExecuteRequestAsync<LSP.CompletionParams, LSP.CompletionList>(LSP.Methods.TextDocumentCompletionName, completionParams, clientCapabilities, null, CancellationToken.None); // Emulate client behavior of promoting "Data" completion list properties onto completion items. if (clientCapabilities.HasCompletionListDataCapability() && completionList is VSInternalCompletionList vsCompletionList && vsCompletionList.Data != null) { foreach (var completionItem in completionList.Items) { Assert.Null(completionItem.Data); completionItem.Data = vsCompletionList.Data; } } return completionList; } private static T ConvertToClientCompletionItem<T>(T serverCompletionItem) where T : LSP.CompletionItem { var serializedItem = JsonConvert.SerializeObject(serverCompletionItem); var clientCompletionItem = JsonConvert.DeserializeObject<T>(serializedItem); return clientCompletionItem; } private class TestCaretOutOfScopeCompletionService : CompletionService { public override string Language => LanguageNames.CSharp; public override Task<CodeAnalysis.Completion.CompletionList> GetCompletionsAsync( Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string> roles = null, OptionSet options = null, CancellationToken cancellationToken = default) => Task.FromResult(CodeAnalysis.Completion.CompletionList.Empty); public override Task<CompletionChange> GetChangeAsync( Document document, CodeAnalysis.Completion.CompletionItem item, char? commitCharacter = null, CancellationToken cancellationToken = default) { var textChange = new TextChange(span: new TextSpan(start: 77, length: 9), newText: @"public override void M() { throw new System.NotImplementedException(); }"); return Task.FromResult(CompletionChange.Create(textChange, newPosition: 0)); } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/SymbolExtensions.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.Collections.ObjectModel Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module SymbolExtensions <Extension> Friend Function GetCustomTypeInfoPayload(method As MethodSymbol) As ReadOnlyCollection(Of Byte) Return method.DeclaringCompilation.GetCustomTypeInfoPayload(method.ReturnType) End Function <Extension> Public Function IsContainingSymbolOfAllTypeParameters(containingSymbol As Symbol, type As TypeSymbol) As Boolean Return type.VisitType(s_hasInvalidTypeParameterFunc, containingSymbol) Is Nothing End Function Private ReadOnly s_hasInvalidTypeParameterFunc As Func(Of TypeSymbol, Symbol, Boolean) = AddressOf HasInvalidTypeParameter Private Function HasInvalidTypeParameter(type As TypeSymbol, containingSymbol As Symbol) As Boolean If type.TypeKind = TypeKind.TypeParameter Then Dim symbol = type.ContainingSymbol While containingSymbol IsNot Nothing AndAlso containingSymbol.Kind <> SymbolKind.Namespace If containingSymbol = symbol Then Return False End If containingSymbol = containingSymbol.ContainingSymbol End While Return True End If Return False End Function ''' <summary> ''' In VB, the type parameters of state machine classes (i.e. for implementing async ''' or iterator methods) are mangled. We unmangle them here so that the unmangled ''' names will bind properly. (Code gen only uses the ordinal, so the name shouldn't ''' affect behavior). ''' </summary> <Extension> Public Function GetUnmangledName(sourceTypeParameter As TypeParameterSymbol) As String Dim sourceName = sourceTypeParameter.Name If sourceName.StartsWith(GeneratedNameConstants.StateMachineTypeParameterPrefix, StringComparison.Ordinal) Then Debug.Assert(sourceTypeParameter.ContainingSymbol.Name. StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)) Debug.Assert(sourceName.Length > GeneratedNameConstants.StateMachineTypeParameterPrefix.Length) Return sourceName.Substring(GeneratedNameConstants.StateMachineTypeParameterPrefix.Length) End If Return sourceName End Function <Extension> Friend Function IsClosureOrStateMachineType(type As TypeSymbol) As Boolean Return type.IsClosureType() OrElse type.IsStateMachineType() End Function <Extension> Friend Function IsClosureType(type As TypeSymbol) As Boolean Return type.Name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal) End Function <Extension> Friend Function IsStateMachineType(type As TypeSymbol) As Boolean Return type.Name.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) End Function <Extension> Friend Function GetAllTypeParameters(method As MethodSymbol) As ImmutableArray(Of TypeParameterSymbol) Dim builder = ArrayBuilder(Of TypeParameterSymbol).GetInstance() method.ContainingType.GetAllTypeParameters(builder) builder.AddRange(method.TypeParameters) Return builder.ToImmutableAndFree() End Function <Extension> Friend Function IsAnonymousTypeField(field As FieldSymbol, <Out> ByRef unmangledName As String) As Boolean If GeneratedNameParser.GetKind(field.ContainingType.Name) <> GeneratedNameKind.AnonymousType Then unmangledName = Nothing Return False End If unmangledName = field.Name If unmangledName(0) = "$"c Then unmangledName = unmangledName.Substring(1) End If Return True End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Collections.ObjectModel Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Module SymbolExtensions <Extension> Friend Function GetCustomTypeInfoPayload(method As MethodSymbol) As ReadOnlyCollection(Of Byte) Return method.DeclaringCompilation.GetCustomTypeInfoPayload(method.ReturnType) End Function <Extension> Public Function IsContainingSymbolOfAllTypeParameters(containingSymbol As Symbol, type As TypeSymbol) As Boolean Return type.VisitType(s_hasInvalidTypeParameterFunc, containingSymbol) Is Nothing End Function Private ReadOnly s_hasInvalidTypeParameterFunc As Func(Of TypeSymbol, Symbol, Boolean) = AddressOf HasInvalidTypeParameter Private Function HasInvalidTypeParameter(type As TypeSymbol, containingSymbol As Symbol) As Boolean If type.TypeKind = TypeKind.TypeParameter Then Dim symbol = type.ContainingSymbol While containingSymbol IsNot Nothing AndAlso containingSymbol.Kind <> SymbolKind.Namespace If containingSymbol = symbol Then Return False End If containingSymbol = containingSymbol.ContainingSymbol End While Return True End If Return False End Function ''' <summary> ''' In VB, the type parameters of state machine classes (i.e. for implementing async ''' or iterator methods) are mangled. We unmangle them here so that the unmangled ''' names will bind properly. (Code gen only uses the ordinal, so the name shouldn't ''' affect behavior). ''' </summary> <Extension> Public Function GetUnmangledName(sourceTypeParameter As TypeParameterSymbol) As String Dim sourceName = sourceTypeParameter.Name If sourceName.StartsWith(GeneratedNameConstants.StateMachineTypeParameterPrefix, StringComparison.Ordinal) Then Debug.Assert(sourceTypeParameter.ContainingSymbol.Name. StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal)) Debug.Assert(sourceName.Length > GeneratedNameConstants.StateMachineTypeParameterPrefix.Length) Return sourceName.Substring(GeneratedNameConstants.StateMachineTypeParameterPrefix.Length) End If Return sourceName End Function <Extension> Friend Function IsClosureOrStateMachineType(type As TypeSymbol) As Boolean Return type.IsClosureType() OrElse type.IsStateMachineType() End Function <Extension> Friend Function IsClosureType(type As TypeSymbol) As Boolean Return type.Name.StartsWith(GeneratedNameConstants.DisplayClassPrefix, StringComparison.Ordinal) End Function <Extension> Friend Function IsStateMachineType(type As TypeSymbol) As Boolean Return type.Name.StartsWith(GeneratedNameConstants.StateMachineTypeNamePrefix, StringComparison.Ordinal) End Function <Extension> Friend Function GetAllTypeParameters(method As MethodSymbol) As ImmutableArray(Of TypeParameterSymbol) Dim builder = ArrayBuilder(Of TypeParameterSymbol).GetInstance() method.ContainingType.GetAllTypeParameters(builder) builder.AddRange(method.TypeParameters) Return builder.ToImmutableAndFree() End Function <Extension> Friend Function IsAnonymousTypeField(field As FieldSymbol, <Out> ByRef unmangledName As String) As Boolean If GeneratedNameParser.GetKind(field.ContainingType.Name) <> GeneratedNameKind.AnonymousType Then unmangledName = Nothing Return False End If unmangledName = field.Name If unmangledName(0) = "$"c Then unmangledName = unmangledName.Substring(1) End If Return True End Function End Module End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/DebuggerDisplayAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase { [Fact] public void WithoutExpressionHoles() { var source = @" using System.Diagnostics; class C0 { } [DebuggerDisplay(""Value"")] class C1 { } [DebuggerDisplay(""Value"", Name=""Name"")] class C2 { } [DebuggerDisplay(""Value"", Type=""Type"")] class C3 { } [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class C4 { } class Wrapper { C0 c0 = new C0(); C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None), EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None)); } [Fact] public void OnlyExpressionHoles() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("c", value)), EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void FormatStrings() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BindingError() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{missing}>"")] class C { } "; const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it. var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks. } [Fact] public void RecursiveDebuggerDisplay() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"")] class C { C value; C() { this.value = this; } } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // No stack overflow, since attribute on computed value is ignored. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); } [Fact] public void MultipleAttributes() { var source = @" using System.Diagnostics; [DebuggerDisplay(""V1"")] [DebuggerDisplay(""V2"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // First attribute wins, as in dev12. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "V1", "C", rootExpr)); } [Fact] public void NullValues() { var source = @" using System.Diagnostics; [DebuggerDisplay(null, Name=null, Type=null)] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr)); } [Fact] public void EmptyStringValues() { var source = @" using System.Diagnostics; [DebuggerDisplay("""", Name="""", Type="""")] class C { } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("", "", "", "w.c")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Name"")] class C<T> { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult("c", "Name", "C<int>", rootExpr)); } [Fact] public void MemberExpansion() { var source = @" using System.Diagnostics; interface I { D P { get; } } class C : I { D I.P { get { return new D(); } } D Q { get { return new D(); } } } [DebuggerDisplay(""Value"", Name=""Name"")] class D { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult(rootExpr, value); Verify(root, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(root), EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name". EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void PointerDereferenceExpansion_Null() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } class Wrapper { Display display = new Display(); } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("wrapper", value); Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3), EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"), EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer")); } [Fact] public void PointerDereferenceExpansion_NonNull() { var source = @" using System; using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe class C { Display* DisplayPointer; NoDisplay* NoDisplayPointer; public C(IntPtr d, IntPtr nd) { this.DisplayPointer = (Display*)d; this.NoDisplayPointer = (NoDisplay*)nd; this.DisplayPointer->DisplayPointer = this.DisplayPointer; this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer; this.NoDisplayPointer->DisplayPointer = this.DisplayPointer; this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer; } } "; var assembly = GetUnsafeAssembly(source); unsafe { var displayType = assembly.GetType("Display"); var displayInstance = displayType.Instantiate(); var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned); var displayPtr = displayHandle.AddrOfPinnedObject(); var noDisplayType = assembly.GetType("NoDisplay"); var noDisplayInstance = noDisplayType.Instantiate(); var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned); var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject(); var testType = assembly.GetType("C"); var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr); var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None); var displayPtrString = PointerToString(displayPtr); var noDisplayPtrString = PointerToString(noDisplayPtr); Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable)); displayHandle.Free(); noDisplayHandle.Free(); } } [Fact] public void ArrayExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] struct Display { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } struct NoDisplay { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } class C { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; public C() { this.DisplayArray = new[] { new Display() }; this.NoDisplayArray = new[] { new NoDisplay() }; this.DisplayArray[0].DisplayArray = this.DisplayArray; this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray; this.NoDisplayArray[0].DisplayArray = this.DisplayArray; this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray; } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void DebuggerTypeProxyExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] public struct Display { } public struct NoDisplay { } [DebuggerTypeProxy(typeof(P))] public class C { public Display DisplayC = new Display(); public NoDisplay NoDisplayC = new NoDisplay(); } public class P { public Display DisplayP = new Display(); public NoDisplay NoDisplayP = new NoDisplay(); public P(C c) { } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "new P(c).DisplayP"), EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"), EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Name", "Value", "Type", "c.DisplayC"), EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC")); } [Fact] public void NullInstance() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Hello"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "null", "C", rootExpr)); } [Fact] public void NonGenericDisplayAttributeOnGenericBase() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Type={GetType()}"")] class A<T> { } class B : A<int> { } "; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var result = FormatResult("b", value); Verify(result, EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None)); } [WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")] [Fact] public void RootVersusInternal() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name = ""Name"")] class A { } class B { A a; public B(A a) { this.a = a; } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var instanceA = typeA.Instantiate(); var instanceB = typeB.Instantiate(instanceA); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)); result = FormatResult("b", CreateDkmClrValue(instanceB)); Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None)); } [Fact] public void Error() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class A { } class B { bool f; internal A P { get { return new A(); } } internal A Q { get { while(f) { } return new A(); } } } "; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.CanFavorite)); } } [Fact] public void UnhandledException() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value}"")] class A { internal int Value; } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var instanceA = typeA.Instantiate(); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None)); } [Fact, WorkItem(171123, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv")] public void ExceptionDuringEvaluate() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Make it throw."")] public class Picard { } "; var assembly = GetAssembly(source); var picard = assembly.GetType("Picard"); var jeanLuc = picard.Instantiate(); var result = FormatAsyncResult("says", "says", CreateDkmClrValue(jeanLuc), declaredType: new BadType(picard)); Assert.Equal(BadType.Exception, result.Exception); } private class BadType : DkmClrType { public static readonly Exception Exception = new TargetInvocationException(new DkmException(DkmExceptionCode.E_PROCESS_DESTROYED)); public BadType(System.Type innerType) : base((TypeImpl)innerType) { } public override VisualStudio.Debugger.Metadata.Type GetLmrType() { if (Environment.StackTrace.Contains("Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.GetTypeName")) { throw Exception; } return base.GetLmrType(); } } private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth) { var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); DepthFirstSearchInternal(builder, root, 0, maxDepth); return builder.ToImmutableAndFree(); } private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth) { Assert.InRange(depth, 0, maxDepth); builder.Add(curr); var childDepth = depth + 1; if (childDepth <= maxDepth) { foreach (var child in GetChildren(curr)) { DepthFirstSearchInternal(builder, child, childDepth, maxDepth); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class DebuggerDisplayAttributeTests : CSharpResultProviderTestBase { [Fact] public void WithoutExpressionHoles() { var source = @" using System.Diagnostics; class C0 { } [DebuggerDisplay(""Value"")] class C1 { } [DebuggerDisplay(""Value"", Name=""Name"")] class C2 { } [DebuggerDisplay(""Value"", Type=""Type"")] class C3 { } [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class C4 { } class Wrapper { C0 c0 = new C0(); C1 c1 = new C1(); C2 c2 = new C2(); C3 c3 = new C3(); C4 c4 = new C4(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("c0", "{C0}", "C0", "w.c0", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("c1", "Value", "C1", "w.c1", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "C2", "w.c2", DkmEvaluationResultFlags.None), EvalResult("c3", "Value", "Type", "w.c3", DkmEvaluationResultFlags.None | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "w.c4", DkmEvaluationResultFlags.None)); } [Fact] public void OnlyExpressionHoles() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"", Name=""{name}"", Type=""{type}"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("c", value)), EvalResult("\"Name\"", "\"Value\"", "\"Type\"", "c.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void FormatStrings() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{value}>"", Name=""<{name}>"", Type=""<{type}>"")] class C { string name = ""Name""; string value = ""Value""; string type = ""Type""; } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("<\"Name\">", "<\"Value\">", "<\"Type\">", "w.c", DkmEvaluationResultFlags.Expandable)); } [Fact] public void BindingError() { var source = @" using System.Diagnostics; [DebuggerDisplay(""<{missing}>"")] class C { } "; const string rootExpr = "c"; // Note that this is the full name in all cases - DebuggerDisplayAttribute does not affect it. var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "<Problem evaluating expression>", "C", rootExpr, DkmEvaluationResultFlags.None)); // Message inlined without quotation marks. } [Fact] public void RecursiveDebuggerDisplay() { var source = @" using System.Diagnostics; [DebuggerDisplay(""{value}"")] class C { C value; C() { this.value = this; } } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // No stack overflow, since attribute on computed value is ignored. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); } [Fact] public void MultipleAttributes() { var source = @" using System.Diagnostics; [DebuggerDisplay(""V1"")] [DebuggerDisplay(""V2"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); // First attribute wins, as in dev12. Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "V1", "C", rootExpr)); } [Fact] public void NullValues() { var source = @" using System.Diagnostics; [DebuggerDisplay(null, Name=null, Type=null)] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "{C}", "C", rootExpr)); } [Fact] public void EmptyStringValues() { var source = @" using System.Diagnostics; [DebuggerDisplay("""", Name="""", Type="""")] class C { } class Wrapper { C c = new C(); } "; var assembly = GetAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(GetChildren(FormatResult("w", value)), EvalResult("", "", "", "w.c")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Name"")] class C<T> { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult("c", "Name", "C<int>", rootExpr)); } [Fact] public void MemberExpansion() { var source = @" using System.Diagnostics; interface I { D P { get; } } class C : I { D I.P { get { return new D(); } } D Q { get { return new D(); } } } [DebuggerDisplay(""Value"", Name=""Name"")] class D { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult(rootExpr, value); Verify(root, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(root), EvalResult("Name", "Value", "D", "((I)c).P", DkmEvaluationResultFlags.ReadOnly), // Not "I.Name". EvalResult("Name", "Value", "D", "c.Q", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void PointerDereferenceExpansion_Null() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { Display* DisplayPointer; NoDisplay* NoDisplayPointer; } class Wrapper { Display display = new Display(); } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("Wrapper"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("wrapper", value); Verify(DepthFirstSearch(GetChildren(root).Single(), maxDepth: 3), EvalResult("Name", "Value", "Type", "wrapper.display", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", PointerToString(IntPtr.Zero), "Display*", "wrapper.display.DisplayPointer"), EvalResult("NoDisplayPointer", PointerToString(IntPtr.Zero), "NoDisplay*", "wrapper.display.NoDisplayPointer")); } [Fact] public void PointerDereferenceExpansion_NonNull() { var source = @" using System; using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] unsafe struct Display { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe struct NoDisplay { public Display* DisplayPointer; public NoDisplay* NoDisplayPointer; } unsafe class C { Display* DisplayPointer; NoDisplay* NoDisplayPointer; public C(IntPtr d, IntPtr nd) { this.DisplayPointer = (Display*)d; this.NoDisplayPointer = (NoDisplay*)nd; this.DisplayPointer->DisplayPointer = this.DisplayPointer; this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer; this.NoDisplayPointer->DisplayPointer = this.DisplayPointer; this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer; } } "; var assembly = GetUnsafeAssembly(source); unsafe { var displayType = assembly.GetType("Display"); var displayInstance = displayType.Instantiate(); var displayHandle = GCHandle.Alloc(displayInstance, GCHandleType.Pinned); var displayPtr = displayHandle.AddrOfPinnedObject(); var noDisplayType = assembly.GetType("NoDisplay"); var noDisplayInstance = noDisplayType.Instantiate(); var noDisplayHandle = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned); var noDisplayPtr = noDisplayHandle.AddrOfPinnedObject(); var testType = assembly.GetType("C"); var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr); var testValue = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None); var displayPtrString = PointerToString(displayPtr); var noDisplayPtrString = PointerToString(noDisplayPtr); Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable)); displayHandle.Free(); noDisplayHandle.Free(); } } [Fact] public void ArrayExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] struct Display { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } struct NoDisplay { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; } class C { public Display[] DisplayArray; public NoDisplay[] NoDisplayArray; public C() { this.DisplayArray = new[] { new Display() }; this.NoDisplayArray = new[] { new NoDisplay() }; this.DisplayArray[0].DisplayArray = this.DisplayArray; this.DisplayArray[0].NoDisplayArray = this.NoDisplayArray; this.NoDisplayArray[0].DisplayArray = this.DisplayArray; this.NoDisplayArray[0].NoDisplayArray = this.NoDisplayArray; } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.DisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.DisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.DisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.DisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("DisplayArray", "{Display[1]}", "Display[]", "c.NoDisplayArray[0].DisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("Name", "Value", "Type", "c.NoDisplayArray[0].DisplayArray[0]", DkmEvaluationResultFlags.Expandable), EvalResult("NoDisplayArray", "{NoDisplay[1]}", "NoDisplay[]", "c.NoDisplayArray[0].NoDisplayArray", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite), EvalResult("[0]", "{NoDisplay}", "NoDisplay", "c.NoDisplayArray[0].NoDisplayArray[0]", DkmEvaluationResultFlags.Expandable)); } [Fact] public void DebuggerTypeProxyExpansion() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] public struct Display { } public struct NoDisplay { } [DebuggerTypeProxy(typeof(P))] public class C { public Display DisplayC = new Display(); public NoDisplay NoDisplayC = new NoDisplay(); } public class P { public Display DisplayP = new Display(); public NoDisplay NoDisplayP = new NoDisplay(); public P(C c) { } } "; var assembly = GetUnsafeAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var root = FormatResult("c", value); Verify(DepthFirstSearch(root, maxDepth: 4), EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable), EvalResult("Name", "Value", "Type", "new P(c).DisplayP"), EvalResult("NoDisplayP", "{NoDisplay}", "NoDisplay", "new P(c).NoDisplayP"), EvalResult("Raw View", null, "", "c, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Name", "Value", "Type", "c.DisplayC"), EvalResult("NoDisplayC", "{NoDisplay}", "NoDisplay", "c.NoDisplayC")); } [Fact] public void NullInstance() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Hello"")] class C { } "; const string rootExpr = "c"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue(null, type, evalFlags: DkmEvaluationResultFlags.None); Verify(FormatResult(rootExpr, value), EvalResult(rootExpr, "null", "C", rootExpr)); } [Fact] public void NonGenericDisplayAttributeOnGenericBase() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Type={GetType()}"")] class A<T> { } class B : A<int> { } "; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue(type.Instantiate(), type, evalFlags: DkmEvaluationResultFlags.None); var result = FormatResult("b", value); Verify(result, EvalResult("b", "Type={B}", "B", "b", DkmEvaluationResultFlags.None)); } [WorkItem(1016895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016895")] [Fact] public void RootVersusInternal() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Value"", Name = ""Name"")] class A { } class B { A a; public B(A a) { this.a = a; } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var instanceA = typeA.Instantiate(); var instanceB = typeB.Instantiate(instanceA); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalResult("a", "Value", "A", "a", DkmEvaluationResultFlags.None)); result = FormatResult("b", CreateDkmClrValue(instanceB)); Verify(GetChildren(result), EvalResult("Name", "Value", "A", "b.a", DkmEvaluationResultFlags.None)); } [Fact] public void Error() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")] class A { } class B { bool f; internal A P { get { return new A(); } } internal A Q { get { while(f) { } return new A(); } } } "; DkmClrRuntimeInstance runtime = null; VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "Q") ? CreateErrorValue(runtime.GetType("A"), "Function evaluation timed out") : null; runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlibAndSystemCore(GetAssembly(source)), getMemberValue: getMemberValue); using (runtime.Load()) { var type = runtime.GetType("B"); var value = type.Instantiate(); var evalResult = FormatResult("o", value); var children = GetChildren(evalResult); Verify(children, EvalResult("Name", "Value", "Type", "o.P", DkmEvaluationResultFlags.ReadOnly), EvalFailedResult("Q", "Function evaluation timed out", "A", "o.Q", DkmEvaluationResultFlags.CanFavorite), EvalResult("f", "false", "bool", "o.f", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.CanFavorite)); } } [Fact] public void UnhandledException() { var source = @"using System.Diagnostics; [DebuggerDisplay(""Value}"")] class A { internal int Value; } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var instanceA = typeA.Instantiate(); var result = FormatResult("a", CreateDkmClrValue(instanceA)); Verify(result, EvalFailedResult("a", "Unmatched closing brace in 'Value}'", null, null, DkmEvaluationResultFlags.None)); } [Fact, WorkItem(171123, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv")] public void ExceptionDuringEvaluate() { var source = @" using System.Diagnostics; [DebuggerDisplay(""Make it throw."")] public class Picard { } "; var assembly = GetAssembly(source); var picard = assembly.GetType("Picard"); var jeanLuc = picard.Instantiate(); var result = FormatAsyncResult("says", "says", CreateDkmClrValue(jeanLuc), declaredType: new BadType(picard)); Assert.Equal(BadType.Exception, result.Exception); } private class BadType : DkmClrType { public static readonly Exception Exception = new TargetInvocationException(new DkmException(DkmExceptionCode.E_PROCESS_DESTROYED)); public BadType(System.Type innerType) : base((TypeImpl)innerType) { } public override VisualStudio.Debugger.Metadata.Type GetLmrType() { if (Environment.StackTrace.Contains("Microsoft.CodeAnalysis.ExpressionEvaluator.ResultProvider.GetTypeName")) { throw Exception; } return base.GetLmrType(); } } private IReadOnlyList<DkmEvaluationResult> DepthFirstSearch(DkmEvaluationResult root, int maxDepth) { var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance(); DepthFirstSearchInternal(builder, root, 0, maxDepth); return builder.ToImmutableAndFree(); } private void DepthFirstSearchInternal(ArrayBuilder<DkmEvaluationResult> builder, DkmEvaluationResult curr, int depth, int maxDepth) { Assert.InRange(depth, 0, maxDepth); builder.Add(curr); var childDepth = depth + 1; if (childDepth <= maxDepth) { foreach (var child in GetChildren(curr)) { DepthFirstSearchInternal(builder, child, childDepth, maxDepth); } } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_InvalidExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using System.Linq; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_InvalidExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_BadReceiver() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Console.WriteLine2()/*</bind>*/; } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'Console.WriteLine2') Children(1): IOperation: (OperationKind.None, Type: null) (Syntax: 'Console') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0117: 'Console' does not contain a definition for 'WriteLine2' // /*<bind>*/Console.WriteLine2()/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMember, "WriteLine2").WithArguments("System.Console", "WriteLine2").WithLocation(8, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureBadArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F(int x) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1503: Argument 1: cannot convert from 'string' to 'int' // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgType, "string.Empty").WithArguments("1", "string", "int").WithLocation(8, 21) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidInvocationExpression_OverloadResolutionFailureExtraArgument() { string source = @" using System; class Program { static void Main(string[] args) { /*<bind>*/F(string.Empty)/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'F(string.Empty)') Children(1): IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String) (Syntax: 'string.Empty') Instance Receiver: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1501: No overload for method 'F' takes 1 arguments // /*<bind>*/F(string.Empty)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadArgCount, "F").WithArguments("F", "1").WithLocation(8, 19) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldReferenceExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); var /*<bind>*/y = x.MissingField/*</bind>*/; } void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: ? y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.MissingField') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.MissingField') IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.MissingField') Children(1): ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1061: 'Program' does not contain a definition for 'MissingField' and no extension method 'MissingField' accepting a first argument of type 'Program' could be found (are you missing a using directive or an assembly reference?) // var y /*<bind>*/= x.MissingField/*</bind>*/; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "MissingField").WithArguments("Program", "MissingField").WithLocation(9, 29) }; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ImplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/string y = x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'string y = x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'string y = x.i1') Declarators: IVariableDeclaratorOperation (Symbol: System.String y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, IsInvalid, IsImplicit) (Syntax: 'x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0029: Cannot implicitly convert type 'int' to 'string' // string y /*<bind>*/= x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x.i1").WithArguments("int", "string").WithLocation(10, 30), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidConversionExpression_ExplicitCast() { string source = @" using System; class Program { int i1; static void Main(string[] args) { var x = new Program(); /*<bind>*/Program y = (Program)x.i1;/*</bind>*/ } void F() { } } "; string expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'Program y = ... ogram)x.i1;') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: 'Program y = ... rogram)x.i1') Declarators: IVariableDeclaratorOperation (Symbol: Program y) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: 'y = (Program)x.i1') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (Program)x.i1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: Program, IsInvalid) (Syntax: '(Program)x.i1') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IFieldReferenceOperation: System.Int32 Program.i1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: 'x.i1') Instance Receiver: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') Initializer: null "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0030: Cannot convert type 'int' to 'Program' // Program y /*<bind>*/= (Program)x.i1/*</bind>*/; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(Program)x.i1").WithArguments("int", "Program").WithLocation(10, 31), // CS0649: Field 'Program.i1' is never assigned to, and will always have its default value 0 // int i1; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "i1").WithArguments("Program.i1", "0").WithLocation(6, 9) }; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidUnaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/++x/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IIncrementOrDecrementOperation (Prefix) (OperationKind.Increment, Type: ?, IsInvalid) (Syntax: '++x') Target: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program, IsInvalid) (Syntax: 'x') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0023: Operator '++' cannot be applied to operand of type 'Program' // Console.Write(/*<bind>*/++x/*</bind>*/); Diagnostic(ErrorCode.ERR_BadUnaryOp, "++x").WithArguments("++", "Program").WithLocation(9, 33) }; VerifyOperationTreeAndDiagnosticsForTest<PrefixUnaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidBinaryExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = new Program(); Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); } void F() { } } "; string expectedOperationTree = @" IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'x + (y * args.Length)') Left: ILocalReferenceOperation: x (OperationKind.LocalReference, Type: Program) (Syntax: 'x') Right: IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: ?, IsInvalid) (Syntax: 'y * args.Length') Left: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y') Children(0) Right: IPropertyReferenceOperation: System.Int32 System.Array.Length { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'args.Length') Instance Receiver: IParameterReferenceOperation: args (OperationKind.ParameterReference, Type: System.String[]) (Syntax: 'args') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'y' does not exist in the current context // Console.Write(/*<bind>*/x + (y * args.Length)/*</bind>*/); Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(9, 38) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_UnboundLambda() { string source = @" using System; class Program { static void Main(string[] args) { var /*<bind>*/x = () => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IVariableDeclaratorOperation (Symbol: System.Action x) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'x = () => F()') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= () => F()') IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action, IsImplicit) (Syntax: '() => F()') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidLambdaBinding_LambdaExpression() { string source = @" using System; class Program { static void Main(string[] args) { var x = /*<bind>*/() => F()/*</bind>*/; } static void F() { } } "; string expectedOperationTree = @" IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: '() => F()') IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'F()') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'F()') Expression: IInvocationOperation (void Program.F()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'F()') Instance Receiver: null Arguments(0) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'F()') ReturnedValue: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidFieldInitializer() { string source = @" class Program { int x /*<bind>*/= Program/*</bind>*/; static void Main(string[] args) { var x = new Program() { x = Program }; } } "; string expectedOperationTree = @" IFieldInitializerOperation (Field: System.Int32 Program.x) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Program') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'Program') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0119: 'Program' is a type, which is not valid in the given context // int x /*<bind>*/= Program/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(4, 23), // CS0119: 'Program' is a type, which is not valid in the given context // var x = new Program() { x = Program }; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(7, 37) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayInitializer() { string source = @" class Program { static void Main(string[] args) { var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { { 1, 1 ... { 2, 2 } }') Element Values(2): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1, 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1, 1 }') Children(1): IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1, 1 }') Element Values(2): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') IArrayInitializerOperation (2 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 2, 2 }') Element Values(2): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1, 1 }").WithLocation(6, 45), // CS0847: An array initializer of length '2' is expected // var x = new int[2, 2] /*<bind>*/{ { { 1, 1 } }, { 2, 2 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "{ { 1, 1 } }").WithArguments("2").WithLocation(6, 43) }; VerifyOperationTreeAndDiagnosticsForTest<InitializerExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidArrayCreation() { string source = @" class Program { static void Main(string[] args) { var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; } } "; string expectedOperationTree = @" IArrayCreationOperation (OperationKind.ArrayCreation, Type: X[], IsInvalid) (Syntax: 'new X[Program] { { 1 } }') Dimension Sizes(1): IInvalidOperation (OperationKind.Invalid, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Program') Children(1): IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Program') Initializer: IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ { 1 } }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: X, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: '{ 1 }') Children(1): IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null, IsInvalid) (Syntax: '{ 1 }') Element Values(1): IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: '1') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(6, 31), // CS0119: 'Program' is a type, which is not valid in the given context // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_BadSKunknown, "Program").WithArguments("Program", "type").WithLocation(6, 33), // CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var x = /*<bind>*/new X[Program] { { 1 } }/*</bind>*/; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 1 }").WithLocation(6, 44) }; VerifyOperationTreeAndDiagnosticsForTest<ArrayCreationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(17598, "https://github.com/dotnet/roslyn/issues/17598")] public void InvalidParameterDefaultValueInitializer() { string source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static int M() { return 0; } void F(int p /*<bind>*/= M()/*</bind>*/) { } } "; string expectedOperationTree = @" IParameterInitializerOperation (Parameter: [System.Int32 p = default(System.Int32)]) (OperationKind.ParameterInitializer, Type: null, IsInvalid) (Syntax: '= M()') IInvocationOperation (System.Int32 Program.M()) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()') Instance Receiver: null Arguments(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1736: Default parameter value for 'p' must be a compile-time constant // void F(int p /*<bind>*/= M()/*</bind>*/) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "M()").WithArguments("p").WithLocation(10, 30) }; VerifyOperationTreeAndDiagnosticsForTest<EqualsValueClauseSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_Repro() { string source = @" public class C { void M() { /*<bind>*/string.Format(format: """", format: """")/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.String, IsInvalid) (Syntax: 'string.Form ... format: """")') Children(3): IOperation: (OperationKind.None, Type: null) (Syntax: 'string') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: """") (Syntax: '""""') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(6,45): error CS1740: Named argument 'format' cannot be specified multiple times // /*<bind>*/string.Format(format: "", format: "")/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "format").WithArguments("format").WithLocation(6, 45) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(a: 1, a: 2, b: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,27): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(a: 1, a: 2)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 27) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(a: 1, a: 2, b: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,32): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(a: 1, a: 2, b: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 32) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,43): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 43) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_CorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[a: 1, a: 2, b: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,30): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[a: 1, a: 2, b: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 30) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Methods() { string source = @" public class C { void N(int a, int b, int c = 4) { } void M() { /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'N(b: 1, a: 2, a: 3)') Children(3): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(10,33): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/N(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(10, 33) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Delegates() { string source = @" public delegate void D(int a, int b, int c = 4); public class C { void N(D lambda) { /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'lambda(b: 1, a: 2, a: 3)') Children(4): IParameterReferenceOperation: lambda (OperationKind.ParameterReference, Type: D) (Syntax: 'lambda') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(7,38): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/lambda(b: 1, a: 2, a: 3)/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(7, 38) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Getter() { string source = @" public class C { int this[int a, int b, int c = 4] { get => 0; } void M() { var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,49): error CS1740: Named argument 'a' cannot be specified multiple times // var result = /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 49) }); } [Fact] [CompilerTrait(CompilerFeature.IOperation)] [WorkItem(20050, "https://github.com/dotnet/roslyn/issues/20050")] public void BuildsArgumentsOperationsForDuplicateExplicitArguments_IncorrectArgumentsOrder_Indexers_Setter() { string source = @" public class C { int this[int a, int b, int c = 4] { set {} } void M() { /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; } }"; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid) (Syntax: 'this[b: 1, a: 2, a: 3]') Children(4): IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') "; VerifyOperationTreeAndDiagnosticsForTest<ElementAccessExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics: new DiagnosticDescription[] { // file.cs(11,36): error CS1740: Named argument 'a' cannot be specified multiple times // /*<bind>*/this[b: 1, a: 2, a: 3]/*</bind>*/ = 0; Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "a").WithArguments("a").WithLocation(11, 36) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_01() { string source = @" using System; class C { static void M1(int i, int x, int y) /*<bind>*/{ i = M(1, __arglist(x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ist(x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... list(x, y))') Left: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __arglist(x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __arglist(x, y))') Children(3): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, y)') Children(2): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_02() { string source = @" using System; class C { static void M1(int i, bool a,int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(x, a ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(x, a ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... a ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... a ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... a ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(x, a ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? y : z') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_03() { string source = @" using System; class C { static void M1(int i, bool a, int w, int x, int y) /*<bind>*/{ i = M(1, __arglist(a ? w : x, y)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, y)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... w : x, y))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... w : x, y))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... w : x, y))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ? w : x, y)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void InvalidExpressionFlow_04() { string source = @" using System; class C { static void M1(int i, bool a, bool b, int w, int x, int y, int z) /*<bind>*/{ i = M(1, __arglist(a ? w : x, b ? y : z)); }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0103: The name 'M' does not exist in the current context // i = M(1, __arglist(a ? w : x, b ? y : z)); Diagnostic(ErrorCode.ERR_NameNotInContext, "M").WithArguments("M").WithLocation(7, 13) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [3] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M') Children(0) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Jump if False (Regular) to Block[B3] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'w') Value: IParameterReferenceOperation: w (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'w') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'x') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'y') Value: IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y') Next (Regular) Block[B7] Block[B6] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'z') Value: IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z') Next (Regular) Block[B7] Block[B7] - Block Predecessors: [B5] [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'i = M(1, __ ... ? y : z));') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'i = M(1, __ ... b ? y : z))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') Right: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M(1, __argl ... b ? y : z))') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) (NoConversion) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'M(1, __argl ... b ? y : z))') Children(3): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'M') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1') IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a ... b ? y : z)') Children(2): IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? w : x') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b ? y : z') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/LiveShare/Impl/Client/Razor/CSharpLspContainedLanguageProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.LiveShare.WebEditors.ContainedLanguage; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Razor { [Export(typeof(IContainedLanguageProvider))] internal class CSharpLspContainedLanguageProvider : IContainedLanguageProvider { private readonly IContentTypeRegistryService _contentTypeRegistry; private readonly SVsServiceProvider _serviceProvider; private readonly CSharpLspRazorProjectFactory _razorProjectFactory; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspContainedLanguageProvider(IContentTypeRegistryService contentTypeRegistry, SVsServiceProvider serviceProvider, CSharpLspRazorProjectFactory razorProjectFactory) { _contentTypeRegistry = contentTypeRegistry ?? throw new ArgumentNullException(nameof(contentTypeRegistry)); _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _razorProjectFactory = razorProjectFactory ?? throw new ArgumentNullException(nameof(razorProjectFactory)); } public IContentType GetContentType(string filePath) => _contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType); public IVsContainedLanguage GetLanguage(string filePath, IVsTextBufferCoordinator bufferCoordinator) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var projectId = _razorProjectFactory.GetProject(filePath); return new ContainedLanguage( bufferCoordinator, componentModel, _razorProjectFactory.Workspace, projectId, project: null, filePath, Guids.CSharpLanguageServiceId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.LiveShare.WebEditors.ContainedLanguage; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.Razor { [Export(typeof(IContainedLanguageProvider))] internal class CSharpLspContainedLanguageProvider : IContainedLanguageProvider { private readonly IContentTypeRegistryService _contentTypeRegistry; private readonly SVsServiceProvider _serviceProvider; private readonly CSharpLspRazorProjectFactory _razorProjectFactory; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpLspContainedLanguageProvider(IContentTypeRegistryService contentTypeRegistry, SVsServiceProvider serviceProvider, CSharpLspRazorProjectFactory razorProjectFactory) { _contentTypeRegistry = contentTypeRegistry ?? throw new ArgumentNullException(nameof(contentTypeRegistry)); _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _razorProjectFactory = razorProjectFactory ?? throw new ArgumentNullException(nameof(razorProjectFactory)); } public IContentType GetContentType(string filePath) => _contentTypeRegistry.GetContentType(ContentTypeNames.CSharpContentType); public IVsContainedLanguage GetLanguage(string filePath, IVsTextBufferCoordinator bufferCoordinator) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var projectId = _razorProjectFactory.GetProject(filePath); return new ContainedLanguage( bufferCoordinator, componentModel, _razorProjectFactory.Workspace, projectId, project: null, filePath, Guids.CSharpLanguageServiceId); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService_Prototype.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Partial Friend Class VisualBasicCodeModelService Private Shared ReadOnly s_prototypeFullNameFormat As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Private Shared ReadOnly s_prototypeTypeNameFormat As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Public Overrides Function GetPrototype(node As SyntaxNode, symbol As ISymbol, flags As PrototypeFlags) As String Debug.Assert(symbol IsNot Nothing) Select Case symbol.Kind Case SymbolKind.Field Return GetVariablePrototype(DirectCast(symbol, IFieldSymbol), flags) Case SymbolKind.Property Dim propertySymbol = DirectCast(symbol, IPropertySymbol) Return GetFunctionPrototype(propertySymbol, propertySymbol.Parameters, flags) Case SymbolKind.Method Dim methodSymbol = DirectCast(symbol, IMethodSymbol) Return GetFunctionPrototype(methodSymbol, methodSymbol.Parameters, flags) Case SymbolKind.NamedType Dim namedTypeSymbol = DirectCast(symbol, INamedTypeSymbol) If namedTypeSymbol.TypeKind = TypeKind.Delegate Then Return GetFunctionPrototype(namedTypeSymbol, namedTypeSymbol.DelegateInvokeMethod.Parameters, flags) End If Case SymbolKind.Event Dim eventSymbol = DirectCast(symbol, IEventSymbol) Dim eventType = TryCast(eventSymbol.Type, INamedTypeSymbol) Dim parameters = If(eventType IsNot Nothing AndAlso eventType.DelegateInvokeMethod IsNot Nothing, eventType.DelegateInvokeMethod.Parameters, ImmutableArray.Create(Of IParameterSymbol)()) Return GetEventPrototype(eventSymbol, parameters, flags) End Select Debug.Fail(String.Format("Invalid symbol kind: {0}", symbol.Kind)) Throw Exceptions.ThrowEUnexpected() End Function Private Function GetEventPrototype(symbol As IEventSymbol, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) As String If Not AreValidFunctionPrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendName(builder, symbol, flags) AppendParameters(builder, parameters, flags) AppendType(builder, symbol.Type, flags) Return builder.ToString() End Function Private Function GetFunctionPrototype(symbol As ISymbol, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) As String If Not AreValidFunctionPrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendName(builder, symbol, flags) AppendParameters(builder, parameters, flags) If symbol.Kind = SymbolKind.Method Then Dim methodSymbol = DirectCast(symbol, IMethodSymbol) If methodSymbol.MethodKind = MethodKind.Ordinary AndAlso methodSymbol.ReturnType IsNot Nothing AndAlso Not methodSymbol.ReturnType.SpecialType = SpecialType.System_Void Then AppendType(builder, methodSymbol.ReturnType, flags) End If End If Return builder.ToString() End Function Private Function GetVariablePrototype(symbol As IFieldSymbol, flags As PrototypeFlags) As String If Not AreValidVariablePrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendAccessibility(builder, symbol.DeclaredAccessibility) builder.Append(" "c) AppendName(builder, symbol, flags) AppendType(builder, symbol.Type, flags) If (flags And PrototypeFlags.Initializer) <> 0 Then Dim modifiedIdentifier = TryCast(symbol.DeclaringSyntaxReferences.FirstOrDefault().GetSyntax(), ModifiedIdentifierSyntax) If modifiedIdentifier IsNot Nothing Then Dim variableDeclarator = TryCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value IsNot Nothing AndAlso Not variableDeclarator.Initializer.Value.IsMissing Then builder.Append(" = ") builder.Append(variableDeclarator.Initializer.Value.ToString()) End If End If End If Return builder.ToString() End Function Private Shared Sub AppendAccessibility(builder As StringBuilder, accessibility As Accessibility) Select accessibility Case Accessibility.Private builder.Append("Private") Case Accessibility.Protected builder.Append("Protected") Case Accessibility.Friend builder.Append("Friend") Case Accessibility.ProtectedOrFriend builder.Append("Protected Friend") Case Accessibility.ProtectedAndFriend builder.Append("Private Protected") Case Accessibility.Public builder.Append("Public") End Select End Sub Private Shared Sub AppendName(builder As StringBuilder, symbol As ISymbol, flags As PrototypeFlags) Select Case flags And PrototypeFlags.NameMask Case PrototypeFlags.FullName builder.Append(symbol.ToDisplayString(s_prototypeFullNameFormat)) Case PrototypeFlags.TypeName builder.Append(symbol.ToDisplayString(s_prototypeTypeNameFormat)) Case PrototypeFlags.BaseName builder.Append(symbol.Name) End Select End Sub Private Sub AppendParameters(builder As StringBuilder, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) builder.Append("("c) If (flags And PrototypeFlags.ParametersMask) <> 0 Then Dim first = True For Each parameter In parameters If Not first Then builder.Append(", ") End If If (flags And PrototypeFlags.ParameterNames) <> 0 Then builder.Append(parameter.Name) builder.Append(" "c) If (flags And PrototypeFlags.ParameterTypes) <> 0 Then builder.Append("As ") End If End If If (flags And PrototypeFlags.ParameterTypes) <> 0 Then builder.Append(parameter.Type.ToDisplayString(s_prototypeFullNameFormat)) End If If (flags And PrototypeFlags.ParameterDefaultValues) <> 0 Then Dim parameterNode = TryCast(parameter.DeclaringSyntaxReferences(0).GetSyntax(), ParameterSyntax) If parameterNode IsNot Nothing AndAlso parameterNode.Default IsNot Nothing AndAlso parameterNode.Default.Value IsNot Nothing AndAlso Not parameterNode.Default.Value.IsMissing Then builder.Append(" = ") builder.Append(parameterNode.Default.Value.ToString()) End If End If Next End If builder.Append(")"c) End Sub Private Shared Sub AppendType(builder As StringBuilder, type As ITypeSymbol, flags As PrototypeFlags) If (flags And PrototypeFlags.Type) <> 0 Then builder.Append(" As ") builder.Append(type.ToDisplayString(s_prototypeFullNameFormat)) End If End Sub Private Shared Function AreValidFunctionPrototypeFlags(flags As PrototypeFlags) As Boolean ' Unsupported flags for functions If (flags And PrototypeFlags.Initializer) <> 0 Then Return False End If Return AreValidPrototypeFlags(flags) End Function Private Shared Function AreValidVariablePrototypeFlags(flags As PrototypeFlags) As Boolean ' Unsupported flags for variables If (flags And PrototypeFlags.ParametersMask) <> 0 Then Return False End If Return AreValidPrototypeFlags(flags) End Function Private Shared Function AreValidPrototypeFlags(ByRef flags As PrototypeFlags) As Boolean ' Signature cannot be combined with anything else If (flags And PrototypeFlags.Signature) <> 0 AndAlso flags <> PrototypeFlags.Signature Then Return False End If ' Only one name flag can be specified Dim nameFlags = flags And PrototypeFlags.NameMask If nameFlags <> 0 Then If Not nameFlags = PrototypeFlags.FullName AndAlso Not nameFlags = PrototypeFlags.TypeName AndAlso Not nameFlags = PrototypeFlags.NoName Then Return False End If End If Return 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 System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Partial Friend Class VisualBasicCodeModelService Private Shared ReadOnly s_prototypeFullNameFormat As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Private Shared ReadOnly s_prototypeTypeNameFormat As SymbolDisplayFormat = New SymbolDisplayFormat( memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.ExpandNullable Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes) Public Overrides Function GetPrototype(node As SyntaxNode, symbol As ISymbol, flags As PrototypeFlags) As String Debug.Assert(symbol IsNot Nothing) Select Case symbol.Kind Case SymbolKind.Field Return GetVariablePrototype(DirectCast(symbol, IFieldSymbol), flags) Case SymbolKind.Property Dim propertySymbol = DirectCast(symbol, IPropertySymbol) Return GetFunctionPrototype(propertySymbol, propertySymbol.Parameters, flags) Case SymbolKind.Method Dim methodSymbol = DirectCast(symbol, IMethodSymbol) Return GetFunctionPrototype(methodSymbol, methodSymbol.Parameters, flags) Case SymbolKind.NamedType Dim namedTypeSymbol = DirectCast(symbol, INamedTypeSymbol) If namedTypeSymbol.TypeKind = TypeKind.Delegate Then Return GetFunctionPrototype(namedTypeSymbol, namedTypeSymbol.DelegateInvokeMethod.Parameters, flags) End If Case SymbolKind.Event Dim eventSymbol = DirectCast(symbol, IEventSymbol) Dim eventType = TryCast(eventSymbol.Type, INamedTypeSymbol) Dim parameters = If(eventType IsNot Nothing AndAlso eventType.DelegateInvokeMethod IsNot Nothing, eventType.DelegateInvokeMethod.Parameters, ImmutableArray.Create(Of IParameterSymbol)()) Return GetEventPrototype(eventSymbol, parameters, flags) End Select Debug.Fail(String.Format("Invalid symbol kind: {0}", symbol.Kind)) Throw Exceptions.ThrowEUnexpected() End Function Private Function GetEventPrototype(symbol As IEventSymbol, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) As String If Not AreValidFunctionPrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendName(builder, symbol, flags) AppendParameters(builder, parameters, flags) AppendType(builder, symbol.Type, flags) Return builder.ToString() End Function Private Function GetFunctionPrototype(symbol As ISymbol, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) As String If Not AreValidFunctionPrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendName(builder, symbol, flags) AppendParameters(builder, parameters, flags) If symbol.Kind = SymbolKind.Method Then Dim methodSymbol = DirectCast(symbol, IMethodSymbol) If methodSymbol.MethodKind = MethodKind.Ordinary AndAlso methodSymbol.ReturnType IsNot Nothing AndAlso Not methodSymbol.ReturnType.SpecialType = SpecialType.System_Void Then AppendType(builder, methodSymbol.ReturnType, flags) End If End If Return builder.ToString() End Function Private Function GetVariablePrototype(symbol As IFieldSymbol, flags As PrototypeFlags) As String If Not AreValidVariablePrototypeFlags(flags) Then Throw Exceptions.ThrowEInvalidArg() End If If flags = PrototypeFlags.Signature Then Return symbol.GetDocumentationCommentId() End If Dim builder = New StringBuilder() AppendAccessibility(builder, symbol.DeclaredAccessibility) builder.Append(" "c) AppendName(builder, symbol, flags) AppendType(builder, symbol.Type, flags) If (flags And PrototypeFlags.Initializer) <> 0 Then Dim modifiedIdentifier = TryCast(symbol.DeclaringSyntaxReferences.FirstOrDefault().GetSyntax(), ModifiedIdentifierSyntax) If modifiedIdentifier IsNot Nothing Then Dim variableDeclarator = TryCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax) If variableDeclarator IsNot Nothing AndAlso variableDeclarator.Initializer IsNot Nothing AndAlso variableDeclarator.Initializer.Value IsNot Nothing AndAlso Not variableDeclarator.Initializer.Value.IsMissing Then builder.Append(" = ") builder.Append(variableDeclarator.Initializer.Value.ToString()) End If End If End If Return builder.ToString() End Function Private Shared Sub AppendAccessibility(builder As StringBuilder, accessibility As Accessibility) Select accessibility Case Accessibility.Private builder.Append("Private") Case Accessibility.Protected builder.Append("Protected") Case Accessibility.Friend builder.Append("Friend") Case Accessibility.ProtectedOrFriend builder.Append("Protected Friend") Case Accessibility.ProtectedAndFriend builder.Append("Private Protected") Case Accessibility.Public builder.Append("Public") End Select End Sub Private Shared Sub AppendName(builder As StringBuilder, symbol As ISymbol, flags As PrototypeFlags) Select Case flags And PrototypeFlags.NameMask Case PrototypeFlags.FullName builder.Append(symbol.ToDisplayString(s_prototypeFullNameFormat)) Case PrototypeFlags.TypeName builder.Append(symbol.ToDisplayString(s_prototypeTypeNameFormat)) Case PrototypeFlags.BaseName builder.Append(symbol.Name) End Select End Sub Private Sub AppendParameters(builder As StringBuilder, parameters As ImmutableArray(Of IParameterSymbol), flags As PrototypeFlags) builder.Append("("c) If (flags And PrototypeFlags.ParametersMask) <> 0 Then Dim first = True For Each parameter In parameters If Not first Then builder.Append(", ") End If If (flags And PrototypeFlags.ParameterNames) <> 0 Then builder.Append(parameter.Name) builder.Append(" "c) If (flags And PrototypeFlags.ParameterTypes) <> 0 Then builder.Append("As ") End If End If If (flags And PrototypeFlags.ParameterTypes) <> 0 Then builder.Append(parameter.Type.ToDisplayString(s_prototypeFullNameFormat)) End If If (flags And PrototypeFlags.ParameterDefaultValues) <> 0 Then Dim parameterNode = TryCast(parameter.DeclaringSyntaxReferences(0).GetSyntax(), ParameterSyntax) If parameterNode IsNot Nothing AndAlso parameterNode.Default IsNot Nothing AndAlso parameterNode.Default.Value IsNot Nothing AndAlso Not parameterNode.Default.Value.IsMissing Then builder.Append(" = ") builder.Append(parameterNode.Default.Value.ToString()) End If End If Next End If builder.Append(")"c) End Sub Private Shared Sub AppendType(builder As StringBuilder, type As ITypeSymbol, flags As PrototypeFlags) If (flags And PrototypeFlags.Type) <> 0 Then builder.Append(" As ") builder.Append(type.ToDisplayString(s_prototypeFullNameFormat)) End If End Sub Private Shared Function AreValidFunctionPrototypeFlags(flags As PrototypeFlags) As Boolean ' Unsupported flags for functions If (flags And PrototypeFlags.Initializer) <> 0 Then Return False End If Return AreValidPrototypeFlags(flags) End Function Private Shared Function AreValidVariablePrototypeFlags(flags As PrototypeFlags) As Boolean ' Unsupported flags for variables If (flags And PrototypeFlags.ParametersMask) <> 0 Then Return False End If Return AreValidPrototypeFlags(flags) End Function Private Shared Function AreValidPrototypeFlags(ByRef flags As PrototypeFlags) As Boolean ' Signature cannot be combined with anything else If (flags And PrototypeFlags.Signature) <> 0 AndAlso flags <> PrototypeFlags.Signature Then Return False End If ' Only one name flag can be specified Dim nameFlags = flags And PrototypeFlags.NameMask If nameFlags <> 0 Then If Not nameFlags = PrototypeFlags.FullName AndAlso Not nameFlags = PrototypeFlags.TypeName AndAlso Not nameFlags = PrototypeFlags.NoName Then Return False End If End If Return True End Function End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/CodeGeneration/CodeGenerationDestination.cs
// Licensed to the .NET Foundation under one or more 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.CodeGeneration { internal enum CodeGenerationDestination { Unspecified = 0, CompilationUnit = 1, Namespace = 2, ClassType = 3, EnumType = 4, InterfaceType = 5, ModuleType = 6, StructType = 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. namespace Microsoft.CodeAnalysis.CodeGeneration { internal enum CodeGenerationDestination { Unspecified = 0, CompilationUnit = 1, Namespace = 2, ClassType = 3, EnumType = 4, InterfaceType = 5, ModuleType = 6, StructType = 7, } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/Core/Portable/SplitOrMergeIfStatements/Consecutive/AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIfStatementCodeRefactoringProvider { // Converts: // if (a || b) // Console.WriteLine(); // // To: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // Converts: // if (a || b) // return; // // To: // if (a) // return; // if (b) // return; // The second case is applied if control flow quits from inside the body. protected sealed override int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds) => syntaxKinds.LogicalOrExpression; protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText) => new MyCodeAction(string.Format(FeaturesResources.Split_into_consecutive_0_statements, ifKeywordText), createChangedDocument); protected sealed override async Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var generator = document.GetLanguageService<SyntaxGenerator>(); leftCondition = leftCondition.WithAdditionalAnnotations(Formatter.Annotation); rightCondition = rightCondition.WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(root, generator); editor.ReplaceNode(ifOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, leftCondition)); if (await CanBeSeparateStatementsAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken).ConfigureAwait(false)) { // Generate: // if (a) // return; // if (b) // return; // At this point, ifLikeStatement must be a standalone if statement with no else clause. Debug.Assert(syntaxFacts.IsExecutableStatement(ifOrElseIf)); Debug.Assert(ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length == 0); var secondIfStatement = ifGenerator.WithCondition(ifOrElseIf, rightCondition) .WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed); if (!syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent)) { // In order to insert a new statement, we have to be inside a block. editor.ReplaceNode(ifOrElseIf, (currentNode, _) => generator.ScopeBlock(ImmutableArray.Create(currentNode))); } editor.InsertAfter(ifOrElseIf, secondIfStatement); } else { // Generate: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // If the if statement is not an else-if clause, we convert it to an else-if clause first (for VB). // Then we insert it right after our current if statement or else-if clause. var elseIfClause = ifGenerator.WithCondition(ifGenerator.ToElseIfClause(ifOrElseIf), rightCondition); ifGenerator.InsertElseIfClause(editor, ifOrElseIf, elseIfClause); } return editor.GetChangedRoot(); } private static async Task<bool> CanBeSeparateStatementsAsync( Document document, ISyntaxFactsService syntaxFacts, IIfLikeStatementGenerator ifGenerator, SyntaxNode ifOrElseIf, CancellationToken cancellationToken) { // In order to make separate statements, ifOrElseIf must be an if statement, not an else-if clause. if (ifGenerator.IsElseIfClause(ifOrElseIf, out _)) { return false; } // If there is an else clause, we *could* in theory separate these and move the current else clause to the second // statement, but we won't. It would break the else-if chain in an odd way. We'll insert an else-if instead. if (ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length > 0) { return false; } var insideStatements = syntaxFacts.GetStatementContainerStatements(ifOrElseIf); if (insideStatements.Count == 0) { // Even though there are no statements inside, we still can't split this into separate statements // because it would change the semantics from short-circuiting to always evaluating the second condition, // breaking code like 'if (a == null || a.InstanceMethod())'. return false; } else { // There are statements inside. We can split this into separate statements and leave out the 'else' if // control flow can't reach the end of these statements (otherwise, it would continue to the second 'if' // and in the case that both conditions are true, run the same statements twice). // This will typically look like a single return, break, continue or a throw statement. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]); return !controlFlow.EndPointIsReachable; } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SplitOrMergeIfStatements { internal abstract class AbstractSplitIntoConsecutiveIfStatementsCodeRefactoringProvider : AbstractSplitIfStatementCodeRefactoringProvider { // Converts: // if (a || b) // Console.WriteLine(); // // To: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // Converts: // if (a || b) // return; // // To: // if (a) // return; // if (b) // return; // The second case is applied if control flow quits from inside the body. protected sealed override int GetLogicalExpressionKind(ISyntaxKindsService syntaxKinds) => syntaxKinds.LogicalOrExpression; protected sealed override CodeAction CreateCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument, string ifKeywordText) => new MyCodeAction(string.Format(FeaturesResources.Split_into_consecutive_0_statements, ifKeywordText), createChangedDocument); protected sealed override async Task<SyntaxNode> GetChangedRootAsync( Document document, SyntaxNode root, SyntaxNode ifOrElseIf, SyntaxNode leftCondition, SyntaxNode rightCondition, CancellationToken cancellationToken) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var ifGenerator = document.GetLanguageService<IIfLikeStatementGenerator>(); var generator = document.GetLanguageService<SyntaxGenerator>(); leftCondition = leftCondition.WithAdditionalAnnotations(Formatter.Annotation); rightCondition = rightCondition.WithAdditionalAnnotations(Formatter.Annotation); var editor = new SyntaxEditor(root, generator); editor.ReplaceNode(ifOrElseIf, (currentNode, _) => ifGenerator.WithCondition(currentNode, leftCondition)); if (await CanBeSeparateStatementsAsync(document, syntaxFacts, ifGenerator, ifOrElseIf, cancellationToken).ConfigureAwait(false)) { // Generate: // if (a) // return; // if (b) // return; // At this point, ifLikeStatement must be a standalone if statement with no else clause. Debug.Assert(syntaxFacts.IsExecutableStatement(ifOrElseIf)); Debug.Assert(ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length == 0); var secondIfStatement = ifGenerator.WithCondition(ifOrElseIf, rightCondition) .WithPrependedLeadingTrivia(generator.ElasticCarriageReturnLineFeed); if (!syntaxFacts.IsExecutableBlock(ifOrElseIf.Parent)) { // In order to insert a new statement, we have to be inside a block. editor.ReplaceNode(ifOrElseIf, (currentNode, _) => generator.ScopeBlock(ImmutableArray.Create(currentNode))); } editor.InsertAfter(ifOrElseIf, secondIfStatement); } else { // Generate: // if (a) // Console.WriteLine(); // else if (b) // Console.WriteLine(); // If the if statement is not an else-if clause, we convert it to an else-if clause first (for VB). // Then we insert it right after our current if statement or else-if clause. var elseIfClause = ifGenerator.WithCondition(ifGenerator.ToElseIfClause(ifOrElseIf), rightCondition); ifGenerator.InsertElseIfClause(editor, ifOrElseIf, elseIfClause); } return editor.GetChangedRoot(); } private static async Task<bool> CanBeSeparateStatementsAsync( Document document, ISyntaxFactsService syntaxFacts, IIfLikeStatementGenerator ifGenerator, SyntaxNode ifOrElseIf, CancellationToken cancellationToken) { // In order to make separate statements, ifOrElseIf must be an if statement, not an else-if clause. if (ifGenerator.IsElseIfClause(ifOrElseIf, out _)) { return false; } // If there is an else clause, we *could* in theory separate these and move the current else clause to the second // statement, but we won't. It would break the else-if chain in an odd way. We'll insert an else-if instead. if (ifGenerator.GetElseIfAndElseClauses(ifOrElseIf).Length > 0) { return false; } var insideStatements = syntaxFacts.GetStatementContainerStatements(ifOrElseIf); if (insideStatements.Count == 0) { // Even though there are no statements inside, we still can't split this into separate statements // because it would change the semantics from short-circuiting to always evaluating the second condition, // breaking code like 'if (a == null || a.InstanceMethod())'. return false; } else { // There are statements inside. We can split this into separate statements and leave out the 'else' if // control flow can't reach the end of these statements (otherwise, it would continue to the second 'if' // and in the case that both conditions are true, run the same statements twice). // This will typically look like a single return, break, continue or a throw statement. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var controlFlow = semanticModel.AnalyzeControlFlow(insideStatements[0], insideStatements[insideStatements.Count - 1]); return !controlFlow.EndPointIsReachable; } } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenRefReturnTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class RefReturnTests : CompilingTestBase { private CompilationVerifier CompileAndVerifyRef( string source, string expectedOutput = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { return CompileAndVerify( source, expectedOutput: expectedOutput, options: options, verify: verify); } [Fact] public void RefReturnRefAssignment() { CompileAndVerify(@" using System; class C { static readonly int _ro = 42; static int _rw = 42; static void Main() { Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; M1(ref _rw)++; Console.WriteLine(M1(ref _rw)); Console.WriteLine(M2(in _ro)); Console.WriteLine(M3(in _ro));; } static ref int M1(ref int rrw) => ref (rrw = ref _rw); static ref readonly int M2(in int rro) => ref (rro = ref _ro); static ref readonly int M3(in int rro) => ref (rro = ref _rw); }", verify: Verification.Fails, expectedOutput: @"42 42 42 43 42 43"); } [Fact] public void RefReturnArrayAccess() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnRefParameter() { var text = @" class Program { static ref int M(ref int i) { return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Skipped).VerifyIL("Program.M(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnOutParameter() { var text = @" class Program { static ref int M(out int i) { i = 0; return ref i; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(out int)", @" { // Code size 5 (0x5) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: stind.i4 IL_0003: ldarg.0 IL_0004: ret }"); } [Fact] public void RefReturnRefLocal() { var text = @" class Program { static ref int M(ref int i) { ref int local = ref i; local = 0; return ref local; } } "; CompileAndVerifyRef(text, verify: Verification.Fails).VerifyIL("Program.M(ref int)", @" { // Code size 5 (0x5) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ret }"); } [Fact] public void RefReturnStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static ref int M() { return ref P; } public static void Main() { var local = 42; // must be real local P = local; P = local; // assign again, should not use stack local System.Console.WriteLine(P); } } "; var v = CompileAndVerifyRef(text, expectedOutput: "42"); v.VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.P.get"" IL_0005: ret }"); v.VerifyIL("Program.Main()", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (int V_0) //local IL_0000: ldc.i4.s 42 IL_0002: stloc.0 IL_0003: call ""ref int Program.P.get"" IL_0008: ldloc.0 IL_0009: stind.i4 IL_000a: call ""ref int Program.P.get"" IL_000f: ldloc.0 IL_0010: stind.i4 IL_0011: call ""ref int Program.P.get"" IL_0016: ldind.i4 IL_0017: call ""void System.Console.WriteLine(int)"" IL_001c: ret }"); } [Fact] public void RefReturnClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int M() { return ref P; } ref int M1() { return ref new Program().P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.P.get"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } ref int M() { return ref P; } ref int M1(ref Program program) { return ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program.P; } } class Program3 { Program program = default(Program); ref int M() { return ref program.P; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program.M1(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: call ""ref int Program.P.get"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.P.get"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.P; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.P; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.P.get"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.P.get"" IL_0011: ret }"); } [Fact] public void RefReturnClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } ref int M() { return ref this[0]; } ref int M1() { return ref new Program()[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 12 (0xc) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: ldc.i4.0 IL_0006: call ""ref int Program.this[int].get"" IL_000b: ret }"); } [Fact] public void RefReturnStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } ref int M() { return ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } ref int M() { return ref program[0]; } } class Program3 { Program program = default(Program); ref int M() { return ref program[0]; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Passes); compilation.VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call ""ref int Program.this[int].get"" IL_0007: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: ret }"); } [Fact] public void RefReturnConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); ref int M() { return ref t[0]; } } class Program2<T> where T : class, I { ref int M(T t) { return ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t[0]; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldc.i4.0 IL_0007: callvirt ""ref int I.this[int].get"" IL_000c: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldc.i4.0 IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.this[int].get"" IL_0012: ret }"); } [Fact] public void RefReturnStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static ref D M() { return ref d; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""D Program.d"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; ref D M() { return ref d; } ref D M1() { return ref new Program().d; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""D Program.d"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""D Program.d"" IL_000a: ret }"); } [Fact] public void RefReturnStaticField() { var text = @" class Program { static int i = 0; static ref int M() { return ref i; } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsflda ""int Program.i"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceField() { var text = @" class Program { int i = 0; ref int M() { return ref i; } ref int M1() { return ref new Program().i; } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: ldflda ""int Program.i"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); ref int M(ref Program program) { return ref program.i; } ref int M() { return ref program.i; } } "; var compilation = CompileAndVerifyRef(text, verify: Verification.Fails); compilation.VerifyIL("Program2.M(ref Program)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldflda ""int Program.i"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldflda ""int Program.i"" IL_000b: ret }"); } [Fact] public void RefReturnStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { return ref M(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.M()"" IL_0005: ret }"); } [Fact] public void RefReturnClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { return ref M(); } ref int M1() { return ref new Program().M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program.M1()", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: newobj ""Program..ctor()"" IL_0005: call ""ref int Program.M()"" IL_000a: ret }"); } [Fact] public void RefReturnStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { return ref M(); } } struct Program2 { Program program; ref int M() { return ref program.M(); } } class Program3 { Program program; ref int M() { return ref program.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""ref int Program.M()"" IL_0006: ret }"); compilation.VerifyIL("Program2.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3.M()", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: call ""ref int Program.M()"" IL_000b: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { return ref t.M(); } } class Program2<T> where T : class, I { ref int M(T t) { return ref t.M(); } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { return ref t.M(); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); compilation.VerifyIL("Program2<T>.M(T)", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: callvirt ""ref int I.M()"" IL_000b: ret }"); compilation.VerifyIL("Program3<T>.M()", @" { // Code size 18 (0x12) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: constrained. ""T"" IL_000c: callvirt ""ref int I.M()"" IL_0011: ret }"); } [Fact] public void RefReturnStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""ref int Program.M(ref int, ref int, object)"" IL_0008: ret }"); } [Fact] public void RefReturnClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } ref int M1(ref int i, ref int j, object o) { return ref new Program().M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 14 (0xe) .maxstack 4 IL_0000: newobj ""Program..ctor()"" IL_0005: ldarg.1 IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: call ""ref int Program.M(ref int, ref int, object)"" IL_000d: ret }"); } [Fact] public void RefReturnStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { return ref M(ref i, ref j, o); } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { return ref program.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: ret }"); compilation.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program2.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); compilation.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 15 (0xf) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""Program Program3.program"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: ret }"); } [Fact] public void RefReturnConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { return ref t.M(ref i, ref j, o); } } "; var compilation = CompileAndVerifyRef(text); compilation.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); compilation.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 4 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: ldarg.2 IL_0007: ldarg.3 IL_0008: ldarg.s V_4 IL_000a: callvirt ""ref int I.M(ref int, ref int, object)"" IL_000f: ret }"); compilation.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldflda ""T Program3<T>.t"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: constrained. ""T"" IL_000f: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0014: ret }"); } [Fact] public void RefReturnDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static ref int M(D d) { return ref d(); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D)", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""ref int D.Invoke()"" IL_0006: ret }"); } [Fact] public void RefReturnDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { return ref d(ref i, ref j, o); } } "; CompileAndVerifyRef(text).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 10 (0xa) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_0009: ret }"); } [Fact] public void RefReturnsAreVariables() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(out int i) { i = 0; } static unsafe void Main() { var program = new Program(); program.P = 0; program.P += 1; program.P++; program.M(ref program.P); program.N(out program.P); fixed (int* i = &program.P) { } var tr = __makeref(program.P); program[0] = 0; program[0] += 1; program[0]++; program.M(ref program[0]); program.N(out program[0]); fixed (int* i = &program[0]) { } tr = __makeref(program[0]); program.M(ref program.field) = 0; program.M(ref program.field) += 1; program.M(ref program.field)++; program.M(ref program.M(ref program.field)); program.N(out program.M(ref program.field)); fixed (int* i = &program.M(ref program.field)) { } tr = __makeref(program.M(ref program.field)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (pinned int& V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: callvirt ""ref int Program.P.get"" IL_000b: ldc.i4.0 IL_000c: stind.i4 IL_000d: dup IL_000e: callvirt ""ref int Program.P.get"" IL_0013: dup IL_0014: ldind.i4 IL_0015: ldc.i4.1 IL_0016: add IL_0017: stind.i4 IL_0018: dup IL_0019: callvirt ""ref int Program.P.get"" IL_001e: dup IL_001f: ldind.i4 IL_0020: ldc.i4.1 IL_0021: add IL_0022: stind.i4 IL_0023: dup IL_0024: dup IL_0025: callvirt ""ref int Program.P.get"" IL_002a: callvirt ""ref int Program.M(ref int)"" IL_002f: pop IL_0030: dup IL_0031: dup IL_0032: callvirt ""ref int Program.P.get"" IL_0037: callvirt ""void Program.N(out int)"" IL_003c: dup IL_003d: callvirt ""ref int Program.P.get"" IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: pop IL_0045: ldc.i4.0 IL_0046: conv.u IL_0047: stloc.0 IL_0048: dup IL_0049: callvirt ""ref int Program.P.get"" IL_004e: mkrefany ""int"" IL_0053: pop IL_0054: dup IL_0055: ldc.i4.0 IL_0056: callvirt ""ref int Program.this[int].get"" IL_005b: ldc.i4.0 IL_005c: stind.i4 IL_005d: dup IL_005e: ldc.i4.0 IL_005f: callvirt ""ref int Program.this[int].get"" IL_0064: dup IL_0065: ldind.i4 IL_0066: ldc.i4.1 IL_0067: add IL_0068: stind.i4 IL_0069: dup IL_006a: ldc.i4.0 IL_006b: callvirt ""ref int Program.this[int].get"" IL_0070: dup IL_0071: ldind.i4 IL_0072: ldc.i4.1 IL_0073: add IL_0074: stind.i4 IL_0075: dup IL_0076: dup IL_0077: ldc.i4.0 IL_0078: callvirt ""ref int Program.this[int].get"" IL_007d: callvirt ""ref int Program.M(ref int)"" IL_0082: pop IL_0083: dup IL_0084: dup IL_0085: ldc.i4.0 IL_0086: callvirt ""ref int Program.this[int].get"" IL_008b: callvirt ""void Program.N(out int)"" IL_0090: dup IL_0091: ldc.i4.0 IL_0092: callvirt ""ref int Program.this[int].get"" IL_0097: stloc.0 IL_0098: ldloc.0 IL_0099: pop IL_009a: ldc.i4.0 IL_009b: conv.u IL_009c: stloc.0 IL_009d: dup IL_009e: ldc.i4.0 IL_009f: callvirt ""ref int Program.this[int].get"" IL_00a4: mkrefany ""int"" IL_00a9: pop IL_00aa: dup IL_00ab: dup IL_00ac: ldflda ""int Program.field"" IL_00b1: callvirt ""ref int Program.M(ref int)"" IL_00b6: ldc.i4.0 IL_00b7: stind.i4 IL_00b8: dup IL_00b9: dup IL_00ba: ldflda ""int Program.field"" IL_00bf: callvirt ""ref int Program.M(ref int)"" IL_00c4: dup IL_00c5: ldind.i4 IL_00c6: ldc.i4.1 IL_00c7: add IL_00c8: stind.i4 IL_00c9: dup IL_00ca: dup IL_00cb: ldflda ""int Program.field"" IL_00d0: callvirt ""ref int Program.M(ref int)"" IL_00d5: dup IL_00d6: ldind.i4 IL_00d7: ldc.i4.1 IL_00d8: add IL_00d9: stind.i4 IL_00da: dup IL_00db: dup IL_00dc: dup IL_00dd: ldflda ""int Program.field"" IL_00e2: callvirt ""ref int Program.M(ref int)"" IL_00e7: callvirt ""ref int Program.M(ref int)"" IL_00ec: pop IL_00ed: dup IL_00ee: dup IL_00ef: dup IL_00f0: ldflda ""int Program.field"" IL_00f5: callvirt ""ref int Program.M(ref int)"" IL_00fa: callvirt ""void Program.N(out int)"" IL_00ff: dup IL_0100: dup IL_0101: ldflda ""int Program.field"" IL_0106: callvirt ""ref int Program.M(ref int)"" IL_010b: stloc.0 IL_010c: ldloc.0 IL_010d: pop IL_010e: ldc.i4.0 IL_010f: conv.u IL_0110: stloc.0 IL_0111: dup IL_0112: ldflda ""int Program.field"" IL_0117: callvirt ""ref int Program.M(ref int)"" IL_011c: mkrefany ""int"" IL_0121: pop IL_0122: ret }"); } [Fact] private void RefReturnsAreValues() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } ref int this[int i] { get { return ref field; } } ref int M(ref int i) { return ref i; } void N(int i) { i = 0; } static unsafe int Main() { var program = new Program(); var @int = program.P + 0; var @string = program.P.ToString(); var @long = (long)program.P; program.N(program.P); @int += program[0] + 0; @string = program[0].ToString(); @long += (long)program[0]; program.N(program[0]); @int += program.M(ref program.field) + 0; @string = program.M(ref program.field).ToString(); @long += (long)program.M(ref program.field); program.N(program.M(ref program.field)); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerifyRef(text, options: TestOptions.UnsafeReleaseDll, verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 168 (0xa8) .maxstack 4 .locals init (Program V_0, //program long V_1) //long IL_0000: newobj ""Program..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt ""ref int Program.P.get"" IL_000c: ldind.i4 IL_000d: ldloc.0 IL_000e: callvirt ""ref int Program.P.get"" IL_0013: call ""string int.ToString()"" IL_0018: pop IL_0019: ldloc.0 IL_001a: callvirt ""ref int Program.P.get"" IL_001f: ldind.i4 IL_0020: conv.i8 IL_0021: stloc.1 IL_0022: ldloc.0 IL_0023: ldloc.0 IL_0024: callvirt ""ref int Program.P.get"" IL_0029: ldind.i4 IL_002a: callvirt ""void Program.N(int)"" IL_002f: ldloc.0 IL_0030: ldc.i4.0 IL_0031: callvirt ""ref int Program.this[int].get"" IL_0036: ldind.i4 IL_0037: add IL_0038: ldloc.0 IL_0039: ldc.i4.0 IL_003a: callvirt ""ref int Program.this[int].get"" IL_003f: call ""string int.ToString()"" IL_0044: pop IL_0045: ldloc.1 IL_0046: ldloc.0 IL_0047: ldc.i4.0 IL_0048: callvirt ""ref int Program.this[int].get"" IL_004d: ldind.i4 IL_004e: conv.i8 IL_004f: add IL_0050: stloc.1 IL_0051: ldloc.0 IL_0052: ldloc.0 IL_0053: ldc.i4.0 IL_0054: callvirt ""ref int Program.this[int].get"" IL_0059: ldind.i4 IL_005a: callvirt ""void Program.N(int)"" IL_005f: ldloc.0 IL_0060: ldloc.0 IL_0061: ldflda ""int Program.field"" IL_0066: callvirt ""ref int Program.M(ref int)"" IL_006b: ldind.i4 IL_006c: add IL_006d: ldloc.0 IL_006e: ldloc.0 IL_006f: ldflda ""int Program.field"" IL_0074: callvirt ""ref int Program.M(ref int)"" IL_0079: call ""string int.ToString()"" IL_007e: pop IL_007f: ldloc.1 IL_0080: ldloc.0 IL_0081: ldloc.0 IL_0082: ldflda ""int Program.field"" IL_0087: callvirt ""ref int Program.M(ref int)"" IL_008c: ldind.i4 IL_008d: conv.i8 IL_008e: add IL_008f: stloc.1 IL_0090: ldloc.0 IL_0091: ldloc.0 IL_0092: ldloc.0 IL_0093: ldflda ""int Program.field"" IL_0098: callvirt ""ref int Program.M(ref int)"" IL_009d: ldind.i4 IL_009e: callvirt ""void Program.N(int)"" IL_00a3: conv.i8 IL_00a4: ldloc.1 IL_00a5: add IL_00a6: conv.i4 IL_00a7: ret }"); } [Fact] public void RefReturnArrayAccessNested() { var text = @" class Program { static ref int M() { ref int N() { return ref (new int[1])[0]; } return ref N(); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular).VerifyIL("Program.M()", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""ref int Program.<M>g__N|0_0()"" IL_0005: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: newarr ""int"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: ret }"); } [Fact] public void RefReturnArrayAccessNested1() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } static void Main() { System.Console.WriteLine(M()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 26 (0x1a) .maxstack 5 .locals init (Program.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0 IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 40 IL_000c: stelem.i4 IL_000d: stfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0012: ldloca.s V_0 IL_0014: call ""ref int Program.<M>g__N|0_0(ref Program.<>c__DisplayClass0_0)"" IL_0019: ret }").VerifyIL("Program.<M>g__N|0_0", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass0_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|0_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|0_1", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnArrayAccessNested2() { var text = @" class Program { delegate ref int D(); static D M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return N; } static void Main() { System.Console.WriteLine(M()()); } } "; CompileAndVerify(text, parseOptions: TestOptions.Regular, expectedOutput: "42", verify: Verification.Fails).VerifyIL("Program.M()", @" { // Code size 36 (0x24) .maxstack 5 .locals init (Program.<>c__DisplayClass1_0 V_0) //CS$<>8__locals0 IL_0000: newobj ""Program.<>c__DisplayClass1_0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: newarr ""int"" IL_000d: dup IL_000e: ldc.i4.0 IL_000f: ldc.i4.s 40 IL_0011: stelem.i4 IL_0012: stfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0017: ldloc.0 IL_0018: ldftn ""ref int Program.<>c__DisplayClass1_0.<M>g__N|0()"" IL_001e: newobj ""Program.D..ctor(object, System.IntPtr)"" IL_0023: ret }").VerifyIL("Program.<>c__DisplayClass1_0.<M>g__N|0()", @" { // Code size 24 (0x18) .maxstack 4 IL_0000: ldarg.0 IL_0001: ldfld ""int[] Program.<>c__DisplayClass1_0.arr"" IL_0006: ldc.i4.0 IL_0007: ldelema ""int"" IL_000c: call ""ref int Program.<M>g__NN|1_1(ref int)"" IL_0011: dup IL_0012: dup IL_0013: ldind.i4 IL_0014: ldc.i4.2 IL_0015: add IL_0016: stind.i4 IL_0017: ret }").VerifyIL("Program.<M>g__NN|1_1(ref int)", @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret }"); } [Fact] public void RefReturnConditionalAccess01() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable() { return ref inst; } public void Test() { GetDisposable().Dispose(); System.Console.Write(inst.ToString()); GetDisposable()?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12") .VerifyIL("Program.C1<T>.Test()", @" { // Code size 114 (0x72) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: call ""ref T Program.C1<T>.GetDisposable()"" IL_0006: constrained. ""T"" IL_000c: callvirt ""void System.IDisposable.Dispose()"" IL_0011: ldarg.0 IL_0012: ldflda ""T Program.C1<T>.inst"" IL_0017: constrained. ""T"" IL_001d: callvirt ""string object.ToString()"" IL_0022: call ""void System.Console.Write(string)"" IL_0027: ldarg.0 IL_0028: call ""ref T Program.C1<T>.GetDisposable()"" IL_002d: ldloca.s V_0 IL_002f: initobj ""T"" IL_0035: ldloc.0 IL_0036: box ""T"" IL_003b: brtrue.s IL_0050 IL_003d: ldobj ""T"" IL_0042: stloc.0 IL_0043: ldloca.s V_0 IL_0045: ldloc.0 IL_0046: box ""T"" IL_004b: brtrue.s IL_0050 IL_004d: pop IL_004e: br.s IL_005b IL_0050: constrained. ""T"" IL_0056: callvirt ""void System.IDisposable.Dispose()"" IL_005b: ldarg.0 IL_005c: ldflda ""T Program.C1<T>.inst"" IL_0061: constrained. ""T"" IL_0067: callvirt ""string object.ToString()"" IL_006c: call ""void System.Console.Write(string)"" IL_0071: ret }"); } [Fact] public void RefReturnConditionalAccess02() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "12", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 115 (0x73) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: dup IL_000d: constrained. ""T"" IL_0013: callvirt ""void System.IDisposable.Dispose()"" IL_0018: ldarg.0 IL_0019: ldflda ""T Program.C1<T>.inst"" IL_001e: constrained. ""T"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.Write(string)"" IL_002e: ldloca.s V_0 IL_0030: initobj ""T"" IL_0036: ldloc.0 IL_0037: box ""T"" IL_003c: brtrue.s IL_0051 IL_003e: ldobj ""T"" IL_0043: stloc.0 IL_0044: ldloca.s V_0 IL_0046: ldloc.0 IL_0047: box ""T"" IL_004c: brtrue.s IL_0051 IL_004e: pop IL_004f: br.s IL_005c IL_0051: constrained. ""T"" IL_0057: callvirt ""void System.IDisposable.Dispose()"" IL_005c: ldarg.0 IL_005d: ldflda ""T Program.C1<T>.inst"" IL_0062: constrained. ""T"" IL_0068: callvirt ""string object.ToString()"" IL_006d: call ""void System.Console.Write(string)"" IL_0072: ret }"); } [Fact] public void RefReturnConditionalAccess03() { var text = @" using System; class Program { class C1<T> where T : IDisposable { T inst = default(T); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp.Dispose(); System.Console.Write(inst.ToString()); temp?.Dispose(); System.Console.Write(inst.ToString()); } } } static void Main(string[] args) { var v = new C1<Mutable>(); v.Test(); } } struct Mutable : IDisposable { public int disposed; public void Dispose() { disposed += 1; } public override string ToString() { return disposed.ToString(); } } "; CompileAndVerifyRef(text, expectedOutput: "1234", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 129 (0x81) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br.s IL_007c IL_0011: ldloc.0 IL_0012: constrained. ""T"" IL_0018: callvirt ""void System.IDisposable.Dispose()"" IL_001d: ldarg.0 IL_001e: ldflda ""T Program.C1<T>.inst"" IL_0023: constrained. ""T"" IL_0029: callvirt ""string object.ToString()"" IL_002e: call ""void System.Console.Write(string)"" IL_0033: ldloc.0 IL_0034: ldloca.s V_2 IL_0036: initobj ""T"" IL_003c: ldloc.2 IL_003d: box ""T"" IL_0042: brtrue.s IL_0057 IL_0044: ldobj ""T"" IL_0049: stloc.2 IL_004a: ldloca.s V_2 IL_004c: ldloc.2 IL_004d: box ""T"" IL_0052: brtrue.s IL_0057 IL_0054: pop IL_0055: br.s IL_0062 IL_0057: constrained. ""T"" IL_005d: callvirt ""void System.IDisposable.Dispose()"" IL_0062: ldarg.0 IL_0063: ldflda ""T Program.C1<T>.inst"" IL_0068: constrained. ""T"" IL_006e: callvirt ""string object.ToString()"" IL_0073: call ""void System.Console.Write(string)"" IL_0078: ldloc.1 IL_0079: ldc.i4.1 IL_007a: add IL_007b: stloc.1 IL_007c: ldloc.1 IL_007d: ldc.i4.2 IL_007e: blt.s IL_0011 IL_0080: ret }"); } [Fact] public void RefReturnConditionalAccess04() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { GetDisposable(ref inst)?.Blah(ref inst); System.Console.Write(inst == null); } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1True", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 84 (0x54) .maxstack 2 .locals init (T V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: ldloca.s V_0 IL_000e: initobj ""T"" IL_0014: ldloc.0 IL_0015: box ""T"" IL_001a: brtrue.s IL_002f IL_001c: ldobj ""T"" IL_0021: stloc.0 IL_0022: ldloca.s V_0 IL_0024: ldloc.0 IL_0025: box ""T"" IL_002a: brtrue.s IL_002f IL_002c: pop IL_002d: br.s IL_0040 IL_002f: ldarg.0 IL_0030: ldflda ""T Program.C1<T>.inst"" IL_0035: constrained. ""T"" IL_003b: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0040: ldarg.0 IL_0041: ldfld ""T Program.C1<T>.inst"" IL_0046: box ""T"" IL_004b: ldnull IL_004c: ceq IL_004e: call ""void System.Console.Write(bool)"" IL_0053: ret }"); } [Fact] public void RefReturnConditionalAccess05() { var text = @" using System; class Program { class C1<T> where T : IGoo<T>, new() { T inst = new T(); public ref T GetDisposable(ref T arg) { return ref arg; } public void Test() { ref T temp = ref GetDisposable(ref inst); // prevent eliding of temp for(int i = 0; i < 2; i++) { temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); inst = new T(); temp?.Blah(ref temp); System.Console.Write(temp == null); System.Console.Write(inst == null); } } } static void Main(string[] args) { var v = new C1<Goo>(); v.Test(); } } interface IGoo<T> { void Blah(ref T arg); } class Goo : IGoo<Goo> { public int disposed; public void Blah(ref Goo arg) { arg = null; disposed++; System.Console.Write(disposed); } } "; CompileAndVerifyRef(text, expectedOutput: "1TrueTrue1TrueTrueTrueTrue1TrueTrue", verify: Verification.Fails) .VerifyIL("Program.C1<T>.Test()", @" { // Code size 215 (0xd7) .maxstack 2 .locals init (T& V_0, //temp int V_1, //i T V_2) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: ldflda ""T Program.C1<T>.inst"" IL_0007: call ""ref T Program.C1<T>.GetDisposable(ref T)"" IL_000c: stloc.0 IL_000d: ldc.i4.0 IL_000e: stloc.1 IL_000f: br IL_00cf IL_0014: ldloc.0 IL_0015: ldloca.s V_2 IL_0017: initobj ""T"" IL_001d: ldloc.2 IL_001e: box ""T"" IL_0023: brtrue.s IL_0038 IL_0025: ldobj ""T"" IL_002a: stloc.2 IL_002b: ldloca.s V_2 IL_002d: ldloc.2 IL_002e: box ""T"" IL_0033: brtrue.s IL_0038 IL_0035: pop IL_0036: br.s IL_0044 IL_0038: ldloc.0 IL_0039: constrained. ""T"" IL_003f: callvirt ""void IGoo<T>.Blah(ref T)"" IL_0044: ldloc.0 IL_0045: ldobj ""T"" IL_004a: box ""T"" IL_004f: ldnull IL_0050: ceq IL_0052: call ""void System.Console.Write(bool)"" IL_0057: ldarg.0 IL_0058: ldfld ""T Program.C1<T>.inst"" IL_005d: box ""T"" IL_0062: ldnull IL_0063: ceq IL_0065: call ""void System.Console.Write(bool)"" IL_006a: ldarg.0 IL_006b: call ""T System.Activator.CreateInstance<T>()"" IL_0070: stfld ""T Program.C1<T>.inst"" IL_0075: ldloc.0 IL_0076: ldloca.s V_2 IL_0078: initobj ""T"" IL_007e: ldloc.2 IL_007f: box ""T"" IL_0084: brtrue.s IL_0099 IL_0086: ldobj ""T"" IL_008b: stloc.2 IL_008c: ldloca.s V_2 IL_008e: ldloc.2 IL_008f: box ""T"" IL_0094: brtrue.s IL_0099 IL_0096: pop IL_0097: br.s IL_00a5 IL_0099: ldloc.0 IL_009a: constrained. ""T"" IL_00a0: callvirt ""void IGoo<T>.Blah(ref T)"" IL_00a5: ldloc.0 IL_00a6: ldobj ""T"" IL_00ab: box ""T"" IL_00b0: ldnull IL_00b1: ceq IL_00b3: call ""void System.Console.Write(bool)"" IL_00b8: ldarg.0 IL_00b9: ldfld ""T Program.C1<T>.inst"" IL_00be: box ""T"" IL_00c3: ldnull IL_00c4: ceq IL_00c6: call ""void System.Console.Write(bool)"" IL_00cb: ldloc.1 IL_00cc: ldc.i4.1 IL_00cd: add IL_00ce: stloc.1 IL_00cf: ldloc.1 IL_00d0: ldc.i4.2 IL_00d1: blt IL_0014 IL_00d6: ret }"); } [Fact] public void RefReturn_CSharp6() { var text = @" class Program { static ref int M() { return ref (new int[1])[0]; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (6,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 16) ); } [Fact] public void RefInLambda_CSharp6() { var text = @" class Program { static ref int M() { var arr = new int[1]{40}; ref int N() { ref int NN(ref int arg) => ref arg; ref var r = ref NN(ref arr[0]); r += 2; return ref r; } return ref N(); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (4,12): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // static ref int M() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(4, 12), // (8,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(8, 9), // (8,17): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int N() Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "N").WithArguments("local functions", "7.0").WithLocation(8, 17), // (10,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 13), // (10,21): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NN").WithArguments("local functions", "7.0").WithLocation(10, 21), // (10,40): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int NN(ref int arg) => ref arg; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(10, 40), // (12,13): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 13), // (12,25): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref var r = ref NN(ref arr[0]); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 25), // (15,20): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref r; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(15, 20), // (18,16): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // return ref N(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(18, 16) ); } [Fact] public void RefDelegate_CSharp6() { var text = @" delegate ref int D(); "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10) ); } [Fact] public void RefInForStatement_CSharp6() { var text = @" class Program { static int M(ref int d) { for (ref int a = ref d; ;) { } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,14): error CS8059: Feature 'ref for-loop variables' is not available in C# 6. Please use language version 7.3 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("ref for-loop variables", "7.3").WithLocation(6, 14), // (6,14): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 14), // (6,26): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // for (ref int a = ref d; ;) { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(6, 26) ); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(int x); class C { static void MD(D d) { } static int i = 0; static void M() { MD((x) => ref i); MD(x => ref i); } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (2,10): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // delegate ref int D(int x); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(2, 10), // (11,19): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD((x) => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(11, 19), // (12,17): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // MD(x => ref i); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(12, 17) ); } [Fact] public void Override_Metadata() { var ilSource = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& A::get_P() } } .class public abstract B1 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object F() { ldnull throw } .method public virtual instance object get_P() { ldnull throw } .property instance object P() { .get instance object B1::get_P() } } .class public abstract B2 extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public virtual instance object& F() { ldnull throw } .method public virtual instance object& get_P() { ldnull throw } .property instance object& P() { .get instance object& B2::get_P() } }"; var ref1 = CompileIL(ilSource); var compilation = CreateCompilation("", options: TestOptions.DebugDll, references: new[] { ref1 }); var method = compilation.GetMember<MethodSymbol>("B1.F"); Assert.Equal("System.Object B1.F()", method.ToTestDisplayString()); Assert.Equal("System.Object A.F()", method.OverriddenMethod.ToTestDisplayString()); var property = compilation.GetMember<PropertySymbol>("B1.P"); Assert.Equal("System.Object B1.P { get; }", property.ToTestDisplayString()); Assert.Null(property.OverriddenProperty); method = compilation.GetMember<MethodSymbol>("B2.F"); Assert.Equal("ref System.Object B2.F()", method.ToTestDisplayString()); Assert.Null(method.OverriddenMethod); property = compilation.GetMember<PropertySymbol>("B2.P"); Assert.Equal("ref System.Object B2.P { get; }", property.ToTestDisplayString()); Assert.Equal("ref System.Object A.P { get; }", property.OverriddenProperty.ToTestDisplayString()); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefReturnFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { return ref _f; } private T _p; public ref T P { get { return ref _p; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [WorkItem(12763, "https://github.com/dotnet/roslyn/issues/12763")] [Fact] public void RefAssignFieldUse001() { var text = @" public class A<T> { private T _f; public ref T F() { ref var r = ref _f; return ref r; } private T _p; public ref T P { get { ref var r = ref _p; return ref r; } } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // no diagnostics expected ); } [Fact] public void ThrowRefReturn() { var text = @"using System; class Program { static ref int P1 { get => throw new E(1); } static ref int P2 => throw new E(2); static ref int M() => throw new E(3); public static void Main() { ref int L() => throw new E(4); D d = () => throw new E(5); try { ref int x = ref P1; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref P2; } catch (E e) { Console.Write(e.Value); } try { ref int x = ref M(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref L(); } catch (E e) { Console.Write(e.Value); } try { ref int x = ref d(); } catch (E e) { Console.Write(e.Value); } } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; var v = CompileAndVerify(text, expectedOutput: "12345"); } [Fact] public void NoRefThrow() { var text = @"using System; class Program { static ref int P1 { get => ref throw new E(1); } static ref int P2 => ref throw new E(2); static ref int M() => ref throw new E(3); public static void Main() { ref int L() => ref throw new E(4); D d = () => ref throw new E(5); L(); d(); } } delegate ref int D(); class E : Exception { public int Value; public E(int value) { this.Value = value; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,36): error CS8115: A throw expression is not allowed in this context. // static ref int P1 { get => ref throw new E(1); } Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(4, 36), // (5,30): error CS8115: A throw expression is not allowed in this context. // static ref int P2 => ref throw new E(2); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 30), // (6,31): error CS8115: A throw expression is not allowed in this context. // static ref int M() => ref throw new E(3); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(6, 31), // (10,28): error CS8115: A throw expression is not allowed in this context. // ref int L() => ref throw new E(4); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(10, 28), // (11,25): error CS8115: A throw expression is not allowed in this context. // D d = () => ref throw new E(5); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 25) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,19): error CS8150: By-value returns may only be used in methods that return by value // B.F(() => o.F(), 2); Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "o.F()").WithLocation(24, 19) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_02() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "2"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Lambda_03() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(() => ref o.F(), 2); System.Console.WriteLine(o.F()); } }"; CreateCompilation(source).VerifyDiagnostics( // (24,23): error CS8149: By-reference returns may only be used in methods that return by reference // B.F(() => ref o.F(), 2); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "o.F()").WithLocation(24, 23) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_01() { var source = @"public delegate ref T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; var v = CompileAndVerify(source, expectedOutput: "23"); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_02() { var source = @"public delegate T D<T>(); public class A<T> { #pragma warning disable 0649 private T _t; public ref T F() { return ref _t; } } public class B { public static void F<T>(D<T> d, T t) { d(); } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); CreateCompilation(source).VerifyDiagnostics( // (24,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(24, 13), // (26,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(26, 24) ); } [Fact] [WorkItem(13206, "https://github.com/dotnet/roslyn/issues/13206")] public void Delegate_03() { var source = @"public delegate ref T D<T>(); public class A<T> { private T _t = default(T); public T F() { return _t; } } public class B { public static void F<T>(D<T> d, T t) { d() = t; } } class Program { static void Main() { var o = new A<int>(); B.F(o.F, 2); System.Console.Write(o.F()); B.F(new D<int>(o.F), 3); System.Console.Write(o.F()); } }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); CreateCompilation(source).VerifyDiagnostics( // (23,13): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(o.F, 2); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(23, 13), // (25,24): error CS8189: Ref mismatch between 'A<int>.F()' and delegate 'D<int>' // B.F(new D<int>(o.F), 3); Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "o.F").WithArguments("A<int>.F()", "D<int>").WithLocation(25, 24) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d.Length); // this is an error return ref d.Length; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (18,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d.Length; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(18, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001a() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref F1(ref d.Length); d = ""qwerty""; ref var temp2 = ref F1(ref d.Length); return temp1; } public static ref dynamic F1(ref dynamic d) { return ref d; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); v.VerifyIL("C.F(ref dynamic)", @" { // Code size 180 (0xb4) .maxstack 8 .locals init (object& V_0, //temp1 object V_1, object V_2) IL_0000: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0005: brtrue.s IL_0036 IL_0007: ldc.i4.0 IL_0008: ldstr ""Length"" IL_000d: ldtoken ""C"" IL_0012: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0017: ldc.i4.1 IL_0018: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_001d: dup IL_001e: ldc.i4.0 IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0026: stelem.ref IL_0027: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_002c: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0031: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0036: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_003b: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_0040: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__0"" IL_0045: ldarg.0 IL_0046: ldind.ref IL_0047: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_004c: stloc.1 IL_004d: ldloca.s V_1 IL_004f: call ""ref dynamic C.F1(ref dynamic)"" IL_0054: stloc.0 IL_0055: ldarg.0 IL_0056: ldstr ""qwerty"" IL_005b: stind.ref IL_005c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0061: brtrue.s IL_0092 IL_0063: ldc.i4.0 IL_0064: ldstr ""Length"" IL_0069: ldtoken ""C"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.1 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.0 IL_007c: ldnull IL_007d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0082: stelem.ref IL_0083: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.GetMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0088: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_008d: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0092: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_0097: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>>.Target"" IL_009c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>> C.<>o__1.<>p__1"" IL_00a1: ldarg.0 IL_00a2: ldind.ref IL_00a3: callvirt ""dynamic System.Func<System.Runtime.CompilerServices.CallSite, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00a8: stloc.2 IL_00a9: ldloca.s V_2 IL_00ab: call ""ref dynamic C.F1(ref dynamic)"" IL_00b0: pop IL_00b1: ldloc.0 IL_00b2: ldind.ref IL_00b3: ret }"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic001b() { var source = @" public class C { public static void Main() { dynamic d = ""qq""; System.Console.WriteLine(F(ref d)); } public static dynamic F(ref dynamic d) { ref var temp1 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); d = ""qwerty""; ref var temp2 = ref Test(arg2: ref F1(42, ref d.Length, 123), arg1: ref F1(42, ref d.Length, 123)); return temp1; } public static ref dynamic F1(in int arg1, ref dynamic d, in int arg2) { if (arg1 == arg2) throw null; return ref d; } public static ref dynamic Test(ref dynamic arg1, ref dynamic arg2) { return ref arg2; } } "; var comp = CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.ReleaseExe); var v = CompileAndVerify(comp, verify: Verification.Fails, expectedOutput: "2"); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic002() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { // this is ok F1(ref d[0]); return ref d[0]; } public static void F1(ref dynamic d) { } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref d[0]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d[0]").WithLocation(17, 20) ); } [Fact] [WorkItem(16947, "https://github.com/dotnet/roslyn/issues/16947")] public void Dynamic003() { var source = @" public class C { public void M() { dynamic d = ""qq""; F(ref d); } public static ref dynamic F(ref dynamic d) { return ref G(ref d.Length); } public static ref dynamic G(ref dynamic d) { return ref d; } } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (14,26): error CS8156: An expression cannot be used in this context because it may not be returned by reference // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "d.Length").WithLocation(14, 26), // (14,20): error CS8347: Cannot use a result of 'C.G(ref dynamic)' in this context because it may expose variables referenced by parameter 'd' outside of their declaration scope // return ref G(ref d.Length); Diagnostic(ErrorCode.ERR_EscapeCall, "G(ref d.Length)").WithArguments("C.G(ref dynamic)", "d").WithLocation(14, 20) ); } [Fact] public void RefReturnVarianceDelegate() { var source = @" using System; delegate ref T RefFunc1<T>(); delegate ref T RefFunc2<in T>(); delegate ref T RefFunc3<out T>(); delegate ref Action<T> RefFunc1a<T>(); delegate ref Action<T> RefFunc2a<in T>(); delegate ref Action<T> RefFunc3a<out T>(); delegate ref Func<T> RefFunc1f<T>(); delegate ref Func<T> RefFunc2f<in T>(); delegate ref Func<T> RefFunc3f<out T>(); "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3<T>.Invoke()'. 'T' is covariant. // delegate ref T RefFunc3<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc3<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(6, 10), // (5,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2<T>.Invoke()'. 'T' is contravariant. // delegate ref T RefFunc2<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("RefFunc2<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(5, 10), // (14,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3f<T>.Invoke()'. 'T' is covariant. // delegate ref Func<T> RefFunc3f<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc3f<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(14, 10), // (13,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2f<T>.Invoke()'. 'T' is contravariant. // delegate ref Func<T> RefFunc2f<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("RefFunc2f<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(13, 10), // (10,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc3a<T>.Invoke()'. 'T' is covariant. // delegate ref Action<T> RefFunc3a<out T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc3a<T>.Invoke()", "T", "covariant", "invariantly").WithLocation(10, 10), // (9,10): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'RefFunc2a<T>.Invoke()'. 'T' is contravariant. // delegate ref Action<T> RefFunc2a<in T>(); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("RefFunc2a<T>.Invoke()", "T", "contravariant", "invariantly").WithLocation(9, 10) ); } [Fact] public void RefReturnVarianceMethod() { var source = @" using System; interface IM1<T> { ref T RefMethod(); } interface IM2<in T> { ref T RefMethod(); } interface IM3<out T> { ref T RefMethod(); } interface IM1a<T> { ref Action<T> RefMethod(); } interface IM2a<in T> { ref Action<T> RefMethod(); } interface IM3a<out T> { ref Action<T> RefMethod(); } interface IM1f<T> { ref Func<T> RefMethod(); } interface IM2f<in T> { ref Func<T> RefMethod(); } interface IM3f<out T> { ref Func<T> RefMethod(); } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3<T>.RefMethod()'. 'T' is covariant. // interface IM3<out T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM3<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(6, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3a<T>.RefMethod()'. 'T' is covariant. // interface IM3a<out T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM3a<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(10, 25), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2a<T>.RefMethod()'. 'T' is contravariant. // interface IM2a<in T> { ref Action<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IM2a<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(9, 24), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2f<T>.RefMethod()'. 'T' is contravariant. // interface IM2f<in T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM2f<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM3f<T>.RefMethod()'. 'T' is covariant. // interface IM3f<out T> { ref Func<T> RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IM3f<T>.RefMethod()", "T", "covariant", "invariantly").WithLocation(14, 25), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IM2<T>.RefMethod()'. 'T' is contravariant. // interface IM2<in T> { ref T RefMethod(); } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IM2<T>.RefMethod()", "T", "contravariant", "invariantly").WithLocation(5, 23) ); } [Fact] public void RefReturnVarianceProperty() { var source = @" using System; interface IP1<T> { ref T RefProp{get;} } interface IP2<in T> { ref T RefProp{get;} } interface IP3<out T> { ref T RefProp{get;} } interface IP1a<T> { ref Action<T> RefProp{get;} } interface IP2a<in T> { ref Action<T> RefProp{get;} } interface IP3a<out T> { ref Action<T> RefProp{get;} } interface IP1f<T> { ref Func<T> RefProp{get;} } interface IP2f<in T> { ref Func<T> RefProp{get;} } interface IP3f<out T> { ref Func<T> RefProp{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.RefProp'. 'T' is contravariant. // interface IP2<in T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(5, 23), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.RefProp'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(13, 24), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.RefProp'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.RefProp", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.RefProp'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.RefProp", "T", "covariant", "invariantly").WithLocation(10, 25), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.RefProp'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.RefProp", "T", "covariant", "invariantly").WithLocation(14, 25), // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.RefProp'. 'T' is covariant. // interface IP3<out T> { ref T RefProp{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.RefProp", "T", "covariant", "invariantly").WithLocation(6, 24) ); } [Fact] public void RefReturnVarianceIndexer() { var source = @" using System; interface IP1<T> { ref T this[int i]{get;} } interface IP2<in T> { ref T this[int i]{get;} } interface IP3<out T> { ref T this[int i]{get;} } interface IP1a<T> { ref Action<T> this[int i]{get;} } interface IP2a<in T> { ref Action<T> this[int i]{get;} } interface IP3a<out T> { ref Action<T> this[int i]{get;} } interface IP1f<T> { ref Func<T> this[int i]{get;} } interface IP2f<in T> { ref Func<T> this[int i]{get;} } interface IP3f<out T> { ref Func<T> this[int i]{get;} } "; CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (6,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3<T>.this[int]'. 'T' is covariant. // interface IP3<out T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP3<T>.this[int]", "T", "covariant", "invariantly").WithLocation(6, 24), // (5,23): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2<T>.this[int]'. 'T' is contravariant. // interface IP2<in T> { ref T this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref T").WithArguments("IP2<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(5, 23), // (9,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2a<T>.this[int]'. 'T' is contravariant. // interface IP2a<in T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP2a<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(9, 24), // (10,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3a<T>.this[int]'. 'T' is covariant. // interface IP3a<out T> { ref Action<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Action<T>").WithArguments("IP3a<T>.this[int]", "T", "covariant", "invariantly").WithLocation(10, 25), // (13,24): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP2f<T>.this[int]'. 'T' is contravariant. // interface IP2f<in T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP2f<T>.this[int]", "T", "contravariant", "invariantly").WithLocation(13, 24), // (14,25): error CS1961: Invalid variance: The type parameter 'T' must be invariantly valid on 'IP3f<T>.this[int]'. 'T' is covariant. // interface IP3f<out T> { ref Func<T> this[int i]{get;} } Diagnostic(ErrorCode.ERR_UnexpectedVariance, "ref Func<T>").WithArguments("IP3f<T>.this[int]", "T", "covariant", "invariantly").WithLocation(14, 25) ); } [Fact] public void RefMethodGroupConversionError() { var source = @" using System; class Program { delegate ref T RefFunc1<T>(); static void Main() { RefFunc1<object> f = M1; f() = 1; f = new RefFunc1<object>(M1); f() = 1; } static ref string M1() => ref new string[]{""qq""}[0]; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string"), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( // (10,30): error CS0407: 'string Program.M1()' has the wrong return type // RefFunc1<object> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(10, 30), // (13,34): error CS0407: 'string Program.M1()' has the wrong return type // f = new RefFunc1<object>(M1); Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1()", "string").WithLocation(13, 34) ); } [Fact] public void RefMethodGroupConversionError_WithResolution() { var source = @" class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => ref Base.Instance; static ref Derived1 M1(Derived1 arg) => ref Derived1.Instance; } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (22,38): error CS0407: 'Derived1 Program.M1(Derived1)' has the wrong return type // RefFunc1<Derived2, Base> f = M1; Diagnostic(ErrorCode.ERR_BadRetType, "M1").WithArguments("Program.M1(Derived1)", "Derived1").WithLocation(22, 38) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupConversionNoError_WithResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1 : Base { public static new Derived1 Instance = new Derived1(); } class Derived2 : Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { RefFunc1<Derived2, Base> f = M1; System.Console.WriteLine(f(null)); } static ref Base M1(Base arg) => throw null; static ref Base M1(Derived1 arg) => ref Base.Instance; } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Base", verify: Verification.Passes); } [Fact] public void RefMethodGroupOverloadResolutionErr() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M1); Test(M3); } static ref Base M1(Derived1 arg) => ref Base.Instance; static ref Base M3(Derived2 arg) => ref Base.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CreateCompilationWithMscorlib45AndCSharp(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyEmitDiagnostics( // (25,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(25, 9), // (26,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Test(Program.RefFunc1<Derived2, Base>)' and 'Program.Test(Program.RefFunc1<Derived2, Derived1>)' // Test(M3); Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("Program.Test(Program.RefFunc1<Derived2, Base>)", "Program.Test(Program.RefFunc1<Derived2, Derived1>)").WithLocation(26, 9) ); CreateCompilationWithMscorlib45AndCSharp(source).VerifyEmitDiagnostics( ); } [Fact] public void RefMethodGroupOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test(M2); } static ref Derived1 M2(Base arg) => ref Derived1.Instance; static void Test(RefFunc1<Derived2, Base> arg) => Console.WriteLine(arg); static void Test(RefFunc1<Derived2, Derived1> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: "Program+RefFunc1`2[Derived2,Derived1]", verify: Verification.Passes); } [Fact] public void RefLambdaOverloadResolution() { var source = @" using System; class Base { public static Base Instance = new Base(); } class Derived1: Base { public static new Derived1 Instance = new Derived1(); } class Derived2: Derived1 { public static new Derived2 Instance = new Derived2(); } class Program { delegate ref TResult RefFunc1<TArg, TResult>(TArg arg); static void Main() { Test((t)=> Base.Instance); Test((t)=> ref Base.Instance); } static void Test(RefFunc1<Derived1, Base> arg) => Console.WriteLine(arg); static void Test(Func<Derived1, Base> arg) => Console.WriteLine(arg); } "; CompileAndVerify(source, parseOptions: TestOptions.Regular, expectedOutput: @"System.Func`2[Derived1,Base] Program+RefFunc1`2[Derived1,Base]", verify: Verification.Passes); } [WorkItem(25024, "https://github.com/dotnet/roslyn/issues/25024")] [Fact] public void RefReturnDiscardLifetime() { var text = @" class Program { static bool flag = true; public static void Main() { if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 1; local2 = 2; System.Console.Write(local1 + local2); } if (flag) { ref var local1 = ref M1(out var _); ref var local2 = ref M1(out var _); local1 = 3; local2 = 4; System.Console.Write(local1 + local2); } } public static ref int M1(out int arg) { arg = 123; return ref arg; } } "; CompileAndVerifyRef(text, expectedOutput: "37", verify: Verification.Fails).VerifyIL("Program.Main()", @" { // Code size 75 (0x4b) .maxstack 3 .locals init (int& V_0, //local2 int V_1, int V_2, int& V_3, //local2 int V_4, int V_5) IL_0000: ldsfld ""bool Program.flag"" IL_0005: brfalse.s IL_0025 IL_0007: ldloca.s V_1 IL_0009: call ""ref int Program.M1(out int)"" IL_000e: ldloca.s V_2 IL_0010: call ""ref int Program.M1(out int)"" IL_0015: stloc.0 IL_0016: dup IL_0017: ldc.i4.1 IL_0018: stind.i4 IL_0019: ldloc.0 IL_001a: ldc.i4.2 IL_001b: stind.i4 IL_001c: ldind.i4 IL_001d: ldloc.0 IL_001e: ldind.i4 IL_001f: add IL_0020: call ""void System.Console.Write(int)"" IL_0025: ldsfld ""bool Program.flag"" IL_002a: brfalse.s IL_004a IL_002c: ldloca.s V_4 IL_002e: call ""ref int Program.M1(out int)"" IL_0033: ldloca.s V_5 IL_0035: call ""ref int Program.M1(out int)"" IL_003a: stloc.3 IL_003b: dup IL_003c: ldc.i4.3 IL_003d: stind.i4 IL_003e: ldloc.3 IL_003f: ldc.i4.4 IL_0040: stind.i4 IL_0041: ldind.i4 IL_0042: ldloc.3 IL_0043: ldind.i4 IL_0044: add IL_0045: call ""void System.Console.Write(int)"" IL_004a: ret }"); } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/VisualStudio/LiveShare/Test/LiveShareTestCompositions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { internal static class LiveShareTestCompositions { public static readonly TestComposition Features = EditorTestCompositions.LanguageServerProtocol .AddAssemblies( typeof(LiveShareResources).Assembly); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests { internal static class LiveShareTestCompositions { public static readonly TestComposition Features = EditorTestCompositions.LanguageServerProtocol .AddAssemblies( typeof(LiveShareResources).Assembly); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Features/CSharp/Portable/Structure/Providers/EnumDeclarationStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class EnumDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EnumDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, EnumDeclarationSyntax enumDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(enumDeclaration, ref spans, optionProvider); if (!enumDeclaration.OpenBraceToken.IsMissing && !enumDeclaration.CloseBraceToken.IsMissing) { SyntaxNodeOrToken current = enumDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between type declarations is collapsed in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( enumDeclaration, enumDeclaration.Identifier, compressEmptyLines: compressEmptyLines, autoCollapse: false, type: BlockTypes.Member, isCollapsible: true)); } // add any leading comments before the end of the type block if (!enumDeclaration.CloseBraceToken.IsMissing) { var leadingTrivia = enumDeclaration.CloseBraceToken.LeadingTrivia; CSharpStructureHelpers.CollectCommentBlockSpans(leadingTrivia, ref spans); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class EnumDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<EnumDeclarationSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, EnumDeclarationSyntax enumDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(enumDeclaration, ref spans, optionProvider); if (!enumDeclaration.OpenBraceToken.IsMissing && !enumDeclaration.CloseBraceToken.IsMissing) { SyntaxNodeOrToken current = enumDeclaration; var nextSibling = current.GetNextSibling(); // Check IsNode to compress blank lines after this node if it is the last child of the parent. // // Whitespace between type declarations is collapsed in Metadata as Source. var compressEmptyLines = optionProvider.IsMetadataAsSource && (!nextSibling.IsNode || nextSibling.AsNode() is BaseTypeDeclarationSyntax); spans.AddIfNotNull(CSharpStructureHelpers.CreateBlockSpan( enumDeclaration, enumDeclaration.Identifier, compressEmptyLines: compressEmptyLines, autoCollapse: false, type: BlockTypes.Member, isCollapsible: true)); } // add any leading comments before the end of the type block if (!enumDeclaration.CloseBraceToken.IsMissing) { var leadingTrivia = enumDeclaration.CloseBraceToken.LeadingTrivia; CSharpStructureHelpers.CollectCommentBlockSpans(leadingTrivia, ref spans); } } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/VisualBasic/Portable/Symbols/LabelSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend MustInherit Class LabelSymbol Inherits Symbol Implements ILabelSymbol Public Sub New(name As String) Me._name = name End Sub Private ReadOnly _name As String Public Overrides ReadOnly Property Name As String Get Return Me._name End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitLabel(Me, arg) End Function Public Overridable ReadOnly Property ContainingMethod As MethodSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return ContainingMethod End Get End Property Public Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Label End Get End Property ' Get the token that defined this label symbol. This is useful for robustly checking ' if a label symbol actually matches a particular definition, even in the presence of duplicates. Friend Overridable ReadOnly Property LabelName As SyntaxToken Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property #Region "ILabelSymbol" Friend ReadOnly Property ILabelSymbol_ContainingMethod As IMethodSymbol Implements ILabelSymbol.ContainingMethod Get Return ContainingMethod End Get End Property #End Region #Region "ISymbol" Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitLabel(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitLabel(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitLabel(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitLabel(Me) End Function #End Region End Class Friend Class GeneratedLabelSymbol Inherits LabelSymbol Public Sub New(name As String) MyBase.New(name) End Sub Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property End Class Friend Class GeneratedUnstructuredExceptionHandlingResumeLabel Inherits GeneratedLabelSymbol ''' <summary> ''' A [Resume] or [On Error Resume Next] statement. ''' </summary> Public ReadOnly ResumeStatement As StatementSyntax Public Sub New(resumeStmt As StatementSyntax) MyBase.New("$VB$UnstructuredExceptionHandling_TargetResumeLabel") Debug.Assert(resumeStmt.Kind = SyntaxKind.OnErrorResumeNextStatement OrElse resumeStmt.Kind = SyntaxKind.ResumeNextStatement OrElse resumeStmt.Kind = SyntaxKind.ResumeStatement) ResumeStatement = resumeStmt End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend MustInherit Class LabelSymbol Inherits Symbol Implements ILabelSymbol Public Sub New(name As String) Me._name = name End Sub Private ReadOnly _name As String Public Overrides ReadOnly Property Name As String Get Return Me._name End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.NotApplicable End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Friend Overloads Overrides Function Accept(Of TArgument, TResult)(visitor As VisualBasicSymbolVisitor(Of TArgument, TResult), arg As TArgument) As TResult Return visitor.VisitLabel(Me, arg) End Function Public Overridable ReadOnly Property ContainingMethod As MethodSymbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return ContainingMethod End Get End Property Public Overrides ReadOnly Property Kind As SymbolKind Get Return SymbolKind.Label End Get End Property ' Get the token that defined this label symbol. This is useful for robustly checking ' if a label symbol actually matches a particular definition, even in the presence of duplicates. Friend Overridable ReadOnly Property LabelName As SyntaxToken Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property #Region "ILabelSymbol" Friend ReadOnly Property ILabelSymbol_ContainingMethod As IMethodSymbol Implements ILabelSymbol.ContainingMethod Get Return ContainingMethod End Get End Property #End Region #Region "ISymbol" Public Overrides Sub Accept(visitor As SymbolVisitor) visitor.VisitLabel(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult Return visitor.VisitLabel(Me) End Function Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor) visitor.VisitLabel(Me) End Sub Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult Return visitor.VisitLabel(Me) End Function #End Region End Class Friend Class GeneratedLabelSymbol Inherits LabelSymbol Public Sub New(name As String) MyBase.New(name) End Sub Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property End Class Friend Class GeneratedUnstructuredExceptionHandlingResumeLabel Inherits GeneratedLabelSymbol ''' <summary> ''' A [Resume] or [On Error Resume Next] statement. ''' </summary> Public ReadOnly ResumeStatement As StatementSyntax Public Sub New(resumeStmt As StatementSyntax) MyBase.New("$VB$UnstructuredExceptionHandling_TargetResumeLabel") Debug.Assert(resumeStmt.Kind = SyntaxKind.OnErrorResumeNextStatement OrElse resumeStmt.Kind = SyntaxKind.ResumeNextStatement OrElse resumeStmt.Kind = SyntaxKind.ResumeStatement) ResumeStatement = resumeStmt End Sub End Class End Namespace
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Tools/ExternalAccess/FSharp/Editor/IFSharpIndentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { /// <summary> /// An indentation result represents where the indent should be placed. It conveys this through /// a pair of values. A position in the existing document where the indent should be relative, /// and the number of columns after that the indent should be placed at. /// /// This pairing provides flexibility to the implementor to compute the indentation results in /// a variety of ways. For example, one implementation may wish to express indentation of a /// newline as being four columns past the start of the first token on a previous line. Another /// may wish to simply express the indentation as an absolute amount from the start of the /// current line. With this tuple, both forms can be expressed, and the implementor does not /// have to convert from one to the other. /// </summary> internal struct FSharpIndentationResult { /// <summary> /// The base position in the document that the indent should be relative to. This position /// can occur on any line (including the current line, or a previous line). /// </summary> public int BasePosition { get; } /// <summary> /// The number of columns the indent should be at relative to the BasePosition's column. /// </summary> public int Offset { get; } public FSharpIndentationResult(int basePosition, int offset) : this() { BasePosition = basePosition; Offset = offset; } } internal interface IFSharpSynchronousIndentationService { /// <summary> /// Determines the desired indentation of a given line. May return <see langword="null"/> if the /// <paramref name="document"/> does not want any sort of automatic indentation. May also return /// <see langword="null"/> if the line in question is not blank and thus indentation should /// be deferred to the formatting command handler to handle. /// </summary> FSharpIndentationResult? GetDesiredIndentation(Document document, int lineNumber, 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; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor { /// <summary> /// An indentation result represents where the indent should be placed. It conveys this through /// a pair of values. A position in the existing document where the indent should be relative, /// and the number of columns after that the indent should be placed at. /// /// This pairing provides flexibility to the implementor to compute the indentation results in /// a variety of ways. For example, one implementation may wish to express indentation of a /// newline as being four columns past the start of the first token on a previous line. Another /// may wish to simply express the indentation as an absolute amount from the start of the /// current line. With this tuple, both forms can be expressed, and the implementor does not /// have to convert from one to the other. /// </summary> internal struct FSharpIndentationResult { /// <summary> /// The base position in the document that the indent should be relative to. This position /// can occur on any line (including the current line, or a previous line). /// </summary> public int BasePosition { get; } /// <summary> /// The number of columns the indent should be at relative to the BasePosition's column. /// </summary> public int Offset { get; } public FSharpIndentationResult(int basePosition, int offset) : this() { BasePosition = basePosition; Offset = offset; } } internal interface IFSharpSynchronousIndentationService { /// <summary> /// Determines the desired indentation of a given line. May return <see langword="null"/> if the /// <paramref name="document"/> does not want any sort of automatic indentation. May also return /// <see langword="null"/> if the line in question is not blank and thus indentation should /// be deferred to the formatting command handler to handle. /// </summary> FSharpIndentationResult? GetDesiredIndentation(Document document, int lineNumber, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ServiceLayer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// The layer of an exported service. /// /// If there are multiple definitions of a service, the <see cref="ServiceLayer"/> is used to determine which is used. /// </summary> public static class ServiceLayer { /// <summary> /// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>. /// </summary> internal const string Test = nameof(Test); /// <summary> /// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>. /// </summary> public const string Host = nameof(Host); /// <summary> /// Service layer that overrides <see cref="Desktop" /> and <see cref="Default"/>. /// </summary> public const string Editor = nameof(Editor); /// <summary> /// Service layer that overrides <see cref="Default"/>. /// </summary> public const string Desktop = nameof(Desktop); /// <summary> /// The base service layer. /// </summary> public const string Default = nameof(Default); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// The layer of an exported service. /// /// If there are multiple definitions of a service, the <see cref="ServiceLayer"/> is used to determine which is used. /// </summary> public static class ServiceLayer { /// <summary> /// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>. /// </summary> internal const string Test = nameof(Test); /// <summary> /// Service layer that overrides <see cref="Editor"/>, <see cref="Desktop"/> and <see cref="Default"/>. /// </summary> public const string Host = nameof(Host); /// <summary> /// Service layer that overrides <see cref="Desktop" /> and <see cref="Default"/>. /// </summary> public const string Editor = nameof(Editor); /// <summary> /// Service layer that overrides <see cref="Default"/>. /// </summary> public const string Desktop = nameof(Desktop); /// <summary> /// The base service layer. /// </summary> public const string Default = nameof(Default); } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/XmlLiteralsInExprLambda01_Result.txt
Lambda( body { Convert( New( Void .ctor(System.String)( Constant( comment type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XDeclaration, System.Object[])( New( Void .ctor(System.String, System.String, System.String)( Constant( 1.0 type: System.String ) Constant( null type: System.String ) Constant( null type: System.String ) ) type: System.Xml.Linq.XDeclaration ) NewArrayInit( Convert( New( Void .ctor(System.String)( Constant( A type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( p type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.String)( Constant( B type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( q type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( r type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( New( Void .ctor(System.String)( Constant( C type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XDocument ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.String)( Constant( B type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( q type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default2 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p4 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default5 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/p5 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 0 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p3 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p3 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 3 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r2 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a.b type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( d type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( c.d type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Constant( 3 type: System.String ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r1 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r2 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( b1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( b1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( q type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: Int32 Count[XElement](System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement]) in System.Linq.Enumerable ( Call( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) ) type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default type: System.String ) ) type: System.Xml.Linq.XName ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] )
Lambda( body { Convert( New( Void .ctor(System.String)( Constant( comment type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XDeclaration, System.Object[])( New( Void .ctor(System.String, System.String, System.String)( Constant( 1.0 type: System.String ) Constant( null type: System.String ) Constant( null type: System.String ) ) type: System.Xml.Linq.XDeclaration ) NewArrayInit( Convert( New( Void .ctor(System.String)( Constant( A type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( p type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.String)( Constant( B type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( q type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( r type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( New( Void .ctor(System.String)( Constant( C type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XDocument ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.String)( Constant( B type: System.String ) ) type: System.Xml.Linq.XComment ) type: System.Object ) Convert( New( Void .ctor(System.String, System.String)( Constant( q type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XProcessingInstruction ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default2 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p4 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default5 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/p5 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 5 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 0 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p3 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p3 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 3 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r2 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a.b type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 2 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( d type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( c.d type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Constant( 3 type: System.String ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( 4 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Xml.Linq.XElement ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r1 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( c type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_x type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( r2 type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/p type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( b1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( a1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( b1 type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( q type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( a type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( MemberAccess( Constant( Form1+_Closure$__1-0 type: Form1+_Closure$__1-0 ) -> $VB$Local_f1 type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( b type: System.String ) Constant( http://roslyn/q type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: Int32 Count[XElement](System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement]) in System.Linq.Enumerable ( Call( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) method: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] Elements(System.Xml.Linq.XName) in System.Xml.Linq.XContainer ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.Collections.Generic.IEnumerable`1[System.Xml.Linq.XElement] ) ) type: System.Int32 ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default type: System.String ) ) type: System.Xml.Linq.XName ) Convert( New( Void .ctor(System.Xml.Linq.XName, System.Object)( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Convert( Constant( http://roslyn/default type: System.String ) type: System.Object ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) Lambda( body { Convert( Call( <NULL> method: System.String get_AttributeValue(System.Xml.Linq.XElement, System.Xml.Linq.XName) in My.InternalXmlHelper ( New( Void .ctor(System.Xml.Linq.XName, System.Object[])( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( x type: System.String ) Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XName ) NewArrayInit( Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( xmlns type: System.String ) Constant( type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/default1 type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) Convert( Call( <NULL> method: System.Xml.Linq.XAttribute CreateNamespaceAttribute(System.Xml.Linq.XName, System.Xml.Linq.XNamespace) in My.InternalXmlHelper ( Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) Call( <NULL> method: System.Xml.Linq.XNamespace Get(System.String) in System.Xml.Linq.XNamespace ( Constant( http://roslyn/p type: System.String ) ) type: System.Xml.Linq.XNamespace ) ) type: System.Xml.Linq.XAttribute ) type: System.Object ) type: System.Object[] ) ) type: System.Xml.Linq.XElement ) Call( <NULL> method: System.Xml.Linq.XName Get(System.String, System.String) in System.Xml.Linq.XName ( Constant( p type: System.String ) Constant( http://www.w3.org/2000/xmlns/ type: System.String ) ) type: System.Xml.Linq.XName ) ) type: System.String ) type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] )
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/EditorFeatures/Core/Tagging/TaggerEventArgs.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Information provided to the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> when /// <see cref="ITaggerEventSource.Changed"/> fires. /// </summary> internal class TaggerEventArgs : EventArgs { public TaggerEventArgs() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Information provided to the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> when /// <see cref="ITaggerEventSource.Changed"/> fires. /// </summary> internal class TaggerEventArgs : EventArgs { public TaggerEventArgs() { } } }
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">新增 'this.'</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">將 'typeof' 轉換為 'nameof'</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">以引數形式傳入擷取到的變數</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">將冒號放在下一行</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">將陳述式放在下一行</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">移除不必要的 Using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">移除大括弧之間的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">移除執行不到的程式碼</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">警告: 新增參數到區域函式宣告可能會產生無效的程式碼。</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">新增 'this.'</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">將 'typeof' 轉換為 'nameof'</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">以引數形式傳入擷取到的變數</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">將冒號放在下一行</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">將陳述式放在下一行</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">移除不必要的 Using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">移除大括弧之間的空白行</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">移除執行不到的程式碼</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">警告: 新增參數到區域函式宣告可能會產生無效的程式碼。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,134
Remove dead code in the compilation tracker.
CyrusNajmabadi
"2021-09-02T20:44:23Z"
"2021-09-02T23:09:41Z"
136930bc1c94db124ee7b0e19f4618a672a260d6
c80e7e6674e0eddc5c70f35ee44684f828ae0473
Remove dead code in the compilation tracker..
./src/Workspaces/Core/MSBuild/Host/Mef/MSBuildMefHostServices.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis.Host.Mef { public static class MSBuildMefHostServices { private static MefHostServices s_defaultServices; public static MefHostServices DefaultServices { get { if (s_defaultServices == null) { Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null); } return s_defaultServices; } } private static ImmutableArray<Assembly> s_defaultAssemblies; public static ImmutableArray<Assembly> DefaultAssemblies { get { if (s_defaultAssemblies == null) { ImmutableInterlocked.InterlockedCompareExchange(ref s_defaultAssemblies, CreateDefaultAssemblies(), default); } return s_defaultAssemblies; } } private static ImmutableArray<Assembly> CreateDefaultAssemblies() { var assemblyNames = new string[] { typeof(MSBuildMefHostServices).Assembly.GetName().Name, }; return MefHostServices.DefaultAssemblies.Concat( MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames)); } internal readonly struct TestAccessor { /// <summary> /// Allows tests to clear services between runs. /// </summary> internal static void ClearCachedServices() { // The existing host, if any, is not retained past this call. s_defaultServices = 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.Collections.Immutable; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis.Host.Mef { public static class MSBuildMefHostServices { private static MefHostServices s_defaultServices; public static MefHostServices DefaultServices { get { if (s_defaultServices == null) { Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null); } return s_defaultServices; } } private static ImmutableArray<Assembly> s_defaultAssemblies; public static ImmutableArray<Assembly> DefaultAssemblies { get { if (s_defaultAssemblies == null) { ImmutableInterlocked.InterlockedCompareExchange(ref s_defaultAssemblies, CreateDefaultAssemblies(), default); } return s_defaultAssemblies; } } private static ImmutableArray<Assembly> CreateDefaultAssemblies() { var assemblyNames = new string[] { typeof(MSBuildMefHostServices).Assembly.GetName().Name, }; return MefHostServices.DefaultAssemblies.Concat( MefHostServicesHelpers.LoadNearbyAssemblies(assemblyNames)); } internal readonly struct TestAccessor { /// <summary> /// Allows tests to clear services between runs. /// </summary> internal static void ClearCachedServices() { // The existing host, if any, is not retained past this call. s_defaultServices = null; } } } }
-1